langchain-google-genai 2.1.7__tar.gz → 2.1.8__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.

Potentially problematic release.


This version of langchain-google-genai might be problematic. Click here for more details.

Files changed (16) hide show
  1. {langchain_google_genai-2.1.7 → langchain_google_genai-2.1.8}/PKG-INFO +1 -1
  2. {langchain_google_genai-2.1.7 → langchain_google_genai-2.1.8}/langchain_google_genai/__init__.py +26 -24
  3. {langchain_google_genai-2.1.7 → langchain_google_genai-2.1.8}/langchain_google_genai/_common.py +8 -8
  4. {langchain_google_genai-2.1.7 → langchain_google_genai-2.1.8}/langchain_google_genai/_genai_extension.py +5 -5
  5. {langchain_google_genai-2.1.7 → langchain_google_genai-2.1.8}/langchain_google_genai/_image_utils.py +3 -3
  6. {langchain_google_genai-2.1.7 → langchain_google_genai-2.1.8}/langchain_google_genai/chat_models.py +17 -17
  7. {langchain_google_genai-2.1.7 → langchain_google_genai-2.1.8}/langchain_google_genai/embeddings.py +124 -20
  8. {langchain_google_genai-2.1.7 → langchain_google_genai-2.1.8}/langchain_google_genai/llms.py +12 -0
  9. {langchain_google_genai-2.1.7 → langchain_google_genai-2.1.8}/pyproject.toml +1 -1
  10. {langchain_google_genai-2.1.7 → langchain_google_genai-2.1.8}/LICENSE +0 -0
  11. {langchain_google_genai-2.1.7 → langchain_google_genai-2.1.8}/README.md +0 -0
  12. {langchain_google_genai-2.1.7 → langchain_google_genai-2.1.8}/langchain_google_genai/_enums.py +0 -0
  13. {langchain_google_genai-2.1.7 → langchain_google_genai-2.1.8}/langchain_google_genai/_function_utils.py +0 -0
  14. {langchain_google_genai-2.1.7 → langchain_google_genai-2.1.8}/langchain_google_genai/genai_aqa.py +0 -0
  15. {langchain_google_genai-2.1.7 → langchain_google_genai-2.1.8}/langchain_google_genai/google_vector_store.py +0 -0
  16. {langchain_google_genai-2.1.7 → langchain_google_genai-2.1.8}/langchain_google_genai/py.typed +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: langchain-google-genai
3
- Version: 2.1.7
3
+ Version: 2.1.8
4
4
  Summary: An integration package connecting Google's genai package and LangChain
5
5
  Home-page: https://github.com/langchain-ai/langchain-google
6
6
  License: MIT
@@ -4,55 +4,57 @@ This module integrates Google's Generative AI models, specifically the Gemini se
4
4
 
5
5
  **Chat Models**
6
6
 
7
- The `ChatGoogleGenerativeAI` class is the primary interface for interacting with Google's Gemini chat models. It allows users to send and receive messages using a specified Gemini model, suitable for various conversational AI applications.
7
+ The ``ChatGoogleGenerativeAI`` class is the primary interface for interacting with Google's Gemini chat models. It allows users to send and receive messages using a specified Gemini model, suitable for various conversational AI applications.
8
8
 
9
9
  **LLMs**
10
10
 
11
- The `GoogleGenerativeAI` class is the primary interface for interacting with Google's Gemini LLMs. It allows users to generate text using a specified Gemini model.
11
+ The ``GoogleGenerativeAI`` class is the primary interface for interacting with Google's Gemini LLMs. It allows users to generate text using a specified Gemini model.
12
12
 
13
13
  **Embeddings**
14
14
 
15
- The `GoogleGenerativeAIEmbeddings` class provides functionalities to generate embeddings using Google's models.
15
+ The ``GoogleGenerativeAIEmbeddings`` class provides functionalities to generate embeddings using Google's models.
16
16
  These embeddings can be used for a range of NLP tasks, including semantic analysis, similarity comparisons, and more.
17
+
17
18
  **Installation**
18
19
 
19
20
  To install the package, use pip:
20
21
 
21
- ```python
22
- pip install -U langchain-google-genai
23
- ```
24
- ## Using Chat Models
22
+ .. code-block:: python
23
+ pip install -U langchain-google-genai
24
+
25
+ **Using Chat Models**
25
26
 
26
27
  After setting up your environment with the required API key, you can interact with the Google Gemini models.
27
28
 
28
- ```python
29
- from langchain_google_genai import ChatGoogleGenerativeAI
29
+ .. code-block:: python
30
+
31
+ from langchain_google_genai import ChatGoogleGenerativeAI
30
32
 
31
- llm = ChatGoogleGenerativeAI(model="gemini-pro")
32
- llm.invoke("Sing a ballad of LangChain.")
33
- ```
33
+ llm = ChatGoogleGenerativeAI(model="gemini-pro")
34
+ llm.invoke("Sing a ballad of LangChain.")
34
35
 
35
- ## Using LLMs
36
+ **Using LLMs**
36
37
 
37
38
  The package also supports generating text with Google's models.
38
39
 
39
- ```python
40
- from langchain_google_genai import GoogleGenerativeAI
40
+ .. code-block:: python
41
41
 
42
- llm = GoogleGenerativeAI(model="gemini-pro")
43
- llm.invoke("Once upon a time, a library called LangChain")
44
- ```
42
+ from langchain_google_genai import GoogleGenerativeAI
45
43
 
46
- ## Embedding Generation
44
+ llm = GoogleGenerativeAI(model="gemini-pro")
45
+ llm.invoke("Once upon a time, a library called LangChain")
46
+
47
+ **Embedding Generation**
47
48
 
48
49
  The package also supports creating embeddings with Google's models, useful for textual similarity and other NLP applications.
49
50
 
50
- ```python
51
- from langchain_google_genai import GoogleGenerativeAIEmbeddings
51
+ .. code-block:: python
52
+
53
+ from langchain_google_genai import GoogleGenerativeAIEmbeddings
54
+
55
+ embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")
56
+ embeddings.embed_query("hello, world!")
52
57
 
53
- embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")
54
- embeddings.embed_query("hello, world!")
55
- ```
56
58
  """ # noqa: E501
57
59
 
58
60
  from langchain_google_genai._enums import HarmBlockThreshold, HarmCategory, Modality
@@ -39,20 +39,19 @@ Supported examples:
39
39
  "when making API calls. If not provided, credentials will be ascertained from "
40
40
  "the GOOGLE_API_KEY envvar"
41
41
  temperature: float = 0.7
42
- """Run inference with this temperature. Must by in the closed interval
43
- [0.0, 2.0]."""
42
+ """Run inference with this temperature. Must be within ``[0.0, 2.0]``."""
44
43
  top_p: Optional[float] = None
45
44
  """Decode using nucleus sampling: consider the smallest set of tokens whose
46
- probability sum is at least top_p. Must be in the closed interval [0.0, 1.0]."""
45
+ probability sum is at least ``top_p``. Must be within ``[0.0, 1.0]``."""
47
46
  top_k: Optional[int] = None
48
- """Decode using top-k sampling: consider the set of top_k most probable tokens.
47
+ """Decode using top-k sampling: consider the set of ``top_k`` most probable tokens.
49
48
  Must be positive."""
50
49
  max_output_tokens: Optional[int] = Field(default=None, alias="max_tokens")
51
50
  """Maximum number of tokens to include in a candidate. Must be greater than zero.
52
- If unset, will default to 64."""
51
+ If unset, will default to ``64``."""
53
52
  n: int = 1
54
53
  """Number of chat completions to generate for each prompt. Note that the API may
55
- not return the full n completions if duplicates are generated."""
54
+ not return the full ``n`` completions if duplicates are generated."""
56
55
  max_retries: int = 6
57
56
  """The maximum number of retries to make when generating."""
58
57
 
@@ -94,6 +93,7 @@ Supported examples:
94
93
 
95
94
  For example:
96
95
 
96
+ .. code-block:: python
97
97
  from google.generativeai.types.safety_types import HarmBlockThreshold, HarmCategory
98
98
 
99
99
  safety_settings = {
@@ -102,7 +102,7 @@ Supported examples:
102
102
  HarmCategory.HARM_CATEGORY_HARASSMENT: HarmBlockThreshold.BLOCK_LOW_AND_ABOVE,
103
103
  HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT: HarmBlockThreshold.BLOCK_NONE,
104
104
  }
105
- """ # noqa: E501
105
+ """ # noqa: E501
106
106
 
107
107
  @property
108
108
  def lc_secrets(self) -> Dict[str, str]:
@@ -149,7 +149,7 @@ def get_client_info(module: Optional[str] = None) -> "ClientInfo":
149
149
  module (Optional[str]):
150
150
  Optional. The module for a custom user agent header.
151
151
  Returns:
152
- google.api_core.gapic_v1.client_info.ClientInfo
152
+ ``google.api_core.gapic_v1.client_info.ClientInfo``
153
153
  """
154
154
  client_library_version, user_agent = get_user_agent(module)
155
155
  return ClientInfo(
@@ -174,12 +174,12 @@ class TestCredentials(credentials.Credentials):
174
174
 
175
175
  @property
176
176
  def expired(self) -> bool:
177
- """Returns `False`, test credentials never expire."""
177
+ """Returns ``False``, test credentials never expire."""
178
178
  return False
179
179
 
180
180
  @property
181
181
  def valid(self) -> bool:
182
- """Returns `True`, test credentials are always valid."""
182
+ """Returns ``True``, test credentials are always valid."""
183
183
  return True
184
184
 
185
185
  def refresh(self, request: Any) -> None:
@@ -206,11 +206,11 @@ class TestCredentials(credentials.Credentials):
206
206
  def _get_credentials() -> Optional[credentials.Credentials]:
207
207
  """Returns credential from config if set or fake credentials for unit testing.
208
208
 
209
- If _config.testing is True, a fake credential is returned.
209
+ If ``_config.testing`` is ``True``, a fake credential is returned.
210
210
  Otherwise, we are in a real environment and will use credentials if provided
211
- or None is returned.
211
+ or ``None`` is returned.
212
212
 
213
- If None is passed to the clients later on, the actual credentials will be
213
+ If ``None`` is passed to the clients later on, the actual credentials will be
214
214
  inferred by the rules specified in google.auth package.
215
215
  """
216
216
  if _config.testing:
@@ -30,7 +30,7 @@ class ImageBytesLoader:
30
30
  """
31
31
 
32
32
  def load_bytes(self, image_string: str) -> bytes:
33
- """Routes to the correct loader based on the image_string.
33
+ """Routes to the correct loader based on the ``'image_string'``.
34
34
 
35
35
  Args:
36
36
  image_string: Can be either:
@@ -178,8 +178,8 @@ def image_bytes_to_b64_string(
178
178
 
179
179
  Args:
180
180
  image_bytes: Bytes of the image.
181
- encoding: Type of encoding in the string. 'ascii' by default.
182
- image_format: Format of the image. 'png' by default.
181
+ encoding: Type of encoding in the string. ``'ascii'`` by default.
182
+ image_format: Format of the image. ``'png'`` by default.
183
183
 
184
184
  Returns:
185
185
  B64 image encoded string.
@@ -31,7 +31,7 @@ from typing import (
31
31
  import filetype # type: ignore[import]
32
32
  import google.api_core
33
33
 
34
- # TODO: remove ignore once the google package is published with types
34
+ # TODO: remove ignore once the Google package is published with types
35
35
  import proto # type: ignore[import]
36
36
  from google.ai.generativelanguage_v1beta import (
37
37
  GenerativeServiceAsyncClient as v1betaGenerativeServiceAsyncClient,
@@ -295,7 +295,7 @@ def _is_openai_image_block(block: dict) -> bool:
295
295
  def _convert_to_parts(
296
296
  raw_content: Union[str, Sequence[Union[str, dict]]],
297
297
  ) -> List[Part]:
298
- """Converts a list of LangChain messages into a google parts."""
298
+ """Converts a list of LangChain messages into a Google parts."""
299
299
  parts = []
300
300
  content = [raw_content] if isinstance(raw_content, str) else raw_content
301
301
  image_loader = ImageBytesLoader()
@@ -413,7 +413,7 @@ def _convert_to_parts(
413
413
  def _convert_tool_message_to_parts(
414
414
  message: ToolMessage | FunctionMessage, name: Optional[str] = None
415
415
  ) -> list[Part]:
416
- """Converts a tool or function message to a google part."""
416
+ """Converts a tool or function message to a Google part."""
417
417
  # Legacy agent stores tool name in message.additional_kwargs instead of message.name
418
418
  name = message.name or name or message.additional_kwargs.get("name")
419
419
  response: Any
@@ -824,8 +824,7 @@ class ChatGoogleGenerativeAI(_BaseGoogleGenerativeAI, BaseChatModel):
824
824
  To use, you must have either:
825
825
 
826
826
  1. The ``GOOGLE_API_KEY`` environment variable set with your API key, or
827
- 2. Pass your API key using the google_api_key kwarg
828
- to the ChatGoogleGenerativeAI constructor.
827
+ 2. Pass your API key using the ``google_api_key`` kwarg to the ChatGoogleGenerativeAI constructor.
829
828
 
830
829
  .. code-block:: python
831
830
 
@@ -893,8 +892,8 @@ class ChatGoogleGenerativeAI(_BaseGoogleGenerativeAI, BaseChatModel):
893
892
 
894
893
  Context Caching:
895
894
  Context caching allows you to store and reuse content (e.g., PDFs, images) for faster processing.
896
- The `cached_content` parameter accepts a cache name created via the Google Generative AI API.
897
- Below are two examples: caching a single file directly and caching multiple files using `Part`.
895
+ The ``cached_content`` parameter accepts a cache name created via the Google Generative AI API.
896
+ Below are two examples: caching a single file directly and caching multiple files using ``Part``.
898
897
 
899
898
  Single File Example:
900
899
  This caches a single file and queries it.
@@ -1140,12 +1139,15 @@ class ChatGoogleGenerativeAI(_BaseGoogleGenerativeAI, BaseChatModel):
1140
1139
 
1141
1140
  response_mime_type: Optional[str] = None
1142
1141
  """Optional. Output response mimetype of the generated candidate text. Only
1143
- supported in Gemini 1.5 and later models. Supported mimetype:
1144
- * "text/plain": (default) Text output.
1145
- * "application/json": JSON response in the candidates.
1146
- * "text/x.enum": Enum in plain text.
1147
- The model also needs to be prompted to output the appropriate response
1148
- type, otherwise the behavior is undefined. This is a preview feature.
1142
+ supported in Gemini 1.5 and later models.
1143
+
1144
+ Supported mimetype:
1145
+ * ``'text/plain'``: (default) Text output.
1146
+ * ``'application/json'``: JSON response in the candidates.
1147
+ * ``'text/x.enum'``: Enum in plain text.
1148
+
1149
+ The model also needs to be prompted to output the appropriate response
1150
+ type, otherwise the behavior is undefined. This is a preview feature.
1149
1151
  """
1150
1152
 
1151
1153
  response_schema: Optional[Dict[str, Any]] = None
@@ -1230,9 +1232,7 @@ class ChatGoogleGenerativeAI(_BaseGoogleGenerativeAI, BaseChatModel):
1230
1232
  if self.top_k is not None and self.top_k <= 0:
1231
1233
  raise ValueError("top_k must be positive")
1232
1234
 
1233
- if not any(
1234
- self.model.startswith(prefix) for prefix in ("models/", "tunedModels/")
1235
- ):
1235
+ if not any(self.model.startswith(prefix) for prefix in ("models/",)):
1236
1236
  self.model = f"models/{self.model}"
1237
1237
 
1238
1238
  additional_headers = self.additional_headers or {}
@@ -1328,7 +1328,7 @@ class ChatGoogleGenerativeAI(_BaseGoogleGenerativeAI, BaseChatModel):
1328
1328
 
1329
1329
  else:
1330
1330
  raise ValueError(
1331
- "Tools are already defined." "code_execution tool can't be defined"
1331
+ "Tools are already defined.code_execution tool can't be defined"
1332
1332
  )
1333
1333
 
1334
1334
  return super().invoke(input, config, stop=stop, **kwargs)
@@ -17,7 +17,10 @@ from langchain_google_genai._common import (
17
17
  GoogleGenerativeAIError,
18
18
  get_client_info,
19
19
  )
20
- from langchain_google_genai._genai_extension import build_generative_service
20
+ from langchain_google_genai._genai_extension import (
21
+ build_generative_async_service,
22
+ build_generative_service,
23
+ )
21
24
 
22
25
  _MAX_TOKENS_PER_BATCH = 20000
23
26
  _DEFAULT_BATCH_SIZE = 100
@@ -29,8 +32,8 @@ class GoogleGenerativeAIEmbeddings(BaseModel, Embeddings):
29
32
  To use, you must have either:
30
33
 
31
34
  1. The ``GOOGLE_API_KEY`` environment variable set with your API key, or
32
- 2. Pass your API key using the google_api_key kwarg
33
- to the GoogleGenerativeAIEmbeddings constructor.
35
+ 2. Pass your API key using the google_api_key kwarg to the
36
+ GoogleGenerativeAIEmbeddings constructor.
34
37
 
35
38
  Example:
36
39
  .. code-block:: python
@@ -42,16 +45,17 @@ class GoogleGenerativeAIEmbeddings(BaseModel, Embeddings):
42
45
  """
43
46
 
44
47
  client: Any = None #: :meta private:
48
+ async_client: Any = None #: :meta private:
45
49
  model: str = Field(
46
50
  ...,
47
51
  description="The name of the embedding model to use. "
48
- "Example: models/embedding-001",
52
+ "Example: ``'models/embedding-001'``",
49
53
  )
50
54
  task_type: Optional[str] = Field(
51
55
  default=None,
52
56
  description="The task type. Valid options include: "
53
- "task_type_unspecified, retrieval_query, retrieval_document, "
54
- "semantic_similarity, classification, and clustering",
57
+ "``'task_type_unspecified'``, ``'retrieval_query'``, ``'retrieval_document'``, "
58
+ "``'semantic_similarity'``, ``'classification'``, and ``'clustering'``",
55
59
  )
56
60
  google_api_key: Optional[SecretStr] = Field(
57
61
  default_factory=secret_from_env("GOOGLE_API_KEY", default=None),
@@ -76,7 +80,7 @@ class GoogleGenerativeAIEmbeddings(BaseModel, Embeddings):
76
80
  )
77
81
  transport: Optional[str] = Field(
78
82
  default=None,
79
- description="A string, one of: [`rest`, `grpc`, `grpc_asyncio`].",
83
+ description="A string, one of: [``'rest'``, ``'grpc'``, ``'grpc_asyncio'``].",
80
84
  )
81
85
  request_options: Optional[Dict] = Field(
82
86
  default=None,
@@ -93,6 +97,9 @@ class GoogleGenerativeAIEmbeddings(BaseModel, Embeddings):
93
97
  google_api_key = self.google_api_key
94
98
  client_info = get_client_info("GoogleGenerativeAIEmbeddings")
95
99
 
100
+ if not any(self.model.startswith(prefix) for prefix in ("models/",)):
101
+ self.model = f"models/{self.model}"
102
+
96
103
  self.client = build_generative_service(
97
104
  credentials=self.credentials,
98
105
  api_key=google_api_key,
@@ -100,6 +107,13 @@ class GoogleGenerativeAIEmbeddings(BaseModel, Embeddings):
100
107
  client_options=self.client_options,
101
108
  transport=self.transport,
102
109
  )
110
+ self.async_client = build_generative_async_service(
111
+ credentials=self.credentials,
112
+ api_key=google_api_key,
113
+ client_info=client_info,
114
+ client_options=self.client_options,
115
+ transport=self.transport,
116
+ )
103
117
  return self
104
118
 
105
119
  @staticmethod
@@ -166,12 +180,12 @@ class GoogleGenerativeAIEmbeddings(BaseModel, Embeddings):
166
180
  def _prepare_request(
167
181
  self,
168
182
  text: str,
183
+ *,
169
184
  task_type: Optional[str] = None,
170
185
  title: Optional[str] = None,
171
186
  output_dimensionality: Optional[int] = None,
172
187
  ) -> EmbedContentRequest:
173
188
  task_type = self.task_type or task_type or "RETRIEVAL_DOCUMENT"
174
- # https://ai.google.dev/api/rest/v1/models/batchEmbedContents#EmbedContentRequest
175
189
  request = EmbedContentRequest(
176
190
  content={"parts": [{"text": text}]},
177
191
  model=self.model,
@@ -190,17 +204,17 @@ class GoogleGenerativeAIEmbeddings(BaseModel, Embeddings):
190
204
  titles: Optional[List[str]] = None,
191
205
  output_dimensionality: Optional[int] = None,
192
206
  ) -> List[List[float]]:
193
- """Embed a list of strings. Google Generative AI currently
194
- sets a max batch size of 100 strings.
207
+ """Embed a list of strings using the `batch endpoint <https://ai.google.dev/api/embeddings#method:-models.batchembedcontents>`__.
208
+
209
+ Google Generative AI currently sets a max batch size of 100 strings.
195
210
 
196
211
  Args:
197
212
  texts: List[str] The list of strings to embed.
198
213
  batch_size: [int] The batch size of embeddings to send to the model
199
- task_type: task_type (https://ai.google.dev/api/rest/v1/TaskType)
214
+ task_type: `task_type <https://ai.google.dev/api/embeddings#tasktype>`__
200
215
  titles: An optional list of titles for texts provided.
201
- Only applicable when TaskType is RETRIEVAL_DOCUMENT.
202
- output_dimensionality: Optional reduced dimension for the output embedding.
203
- https://ai.google.dev/api/rest/v1/models/batchEmbedContents#EmbedContentRequest
216
+ Only applicable when TaskType is ``'RETRIEVAL_DOCUMENT'``.
217
+ output_dimensionality: Optional `reduced dimension for the output embedding <https://ai.google.dev/api/embeddings#EmbedContentRequest>`__.
204
218
  Returns:
205
219
  List of embeddings, one for each text.
206
220
  """
@@ -237,26 +251,26 @@ class GoogleGenerativeAIEmbeddings(BaseModel, Embeddings):
237
251
  def embed_query(
238
252
  self,
239
253
  text: str,
254
+ *,
240
255
  task_type: Optional[str] = None,
241
256
  title: Optional[str] = None,
242
257
  output_dimensionality: Optional[int] = None,
243
258
  ) -> List[float]:
244
- """Embed a text, using the non-batch endpoint:
245
- https://ai.google.dev/api/rest/v1/models/embedContent#EmbedContentRequest
259
+ """Embed a text, using the `non-batch endpoint <https://ai.google.dev/api/embeddings#method:-models.embedcontent>`__.
246
260
 
247
261
  Args:
248
262
  text: The text to embed.
249
- task_type: task_type (https://ai.google.dev/api/rest/v1/TaskType)
263
+ task_type: `task_type <https://ai.google.dev/api/embeddings#tasktype>`__
250
264
  title: An optional title for the text.
251
- Only applicable when TaskType is RETRIEVAL_DOCUMENT.
252
- output_dimensionality: Optional reduced dimension for the output embedding.
265
+ Only applicable when TaskType is ``'RETRIEVAL_DOCUMENT'``.
266
+ output_dimensionality: Optional `reduced dimension for the output embedding <https://ai.google.dev/api/embeddings#EmbedContentRequest>`__.
253
267
 
254
268
  Returns:
255
269
  Embedding for the text.
256
270
  """
257
271
  task_type_to_use = task_type if task_type else self.task_type
258
272
  if task_type_to_use is None:
259
- task_type_to_use = "RETRIEVAL_QUERY" # Default to RETRIEVAL_QUERY
273
+ task_type_to_use = "RETRIEVAL_QUERY"
260
274
  try:
261
275
  request: EmbedContentRequest = self._prepare_request(
262
276
  text=text,
@@ -268,3 +282,93 @@ class GoogleGenerativeAIEmbeddings(BaseModel, Embeddings):
268
282
  except Exception as e:
269
283
  raise GoogleGenerativeAIError(f"Error embedding content: {e}") from e
270
284
  return list(result.embedding.values)
285
+
286
+ async def aembed_documents(
287
+ self,
288
+ texts: List[str],
289
+ *,
290
+ batch_size: int = _DEFAULT_BATCH_SIZE,
291
+ task_type: Optional[str] = None,
292
+ titles: Optional[List[str]] = None,
293
+ output_dimensionality: Optional[int] = None,
294
+ ) -> List[List[float]]:
295
+ """Embed a list of strings using the `batch endpoint <https://ai.google.dev/api/embeddings#method:-models.batchembedcontents>`__.
296
+
297
+ Google Generative AI currently sets a max batch size of 100 strings.
298
+
299
+ Args:
300
+ texts: List[str] The list of strings to embed.
301
+ batch_size: [int] The batch size of embeddings to send to the model
302
+ task_type: `task_type <https://ai.google.dev/api/embeddings#tasktype>`__
303
+ titles: An optional list of titles for texts provided.
304
+ Only applicable when TaskType is ``'RETRIEVAL_DOCUMENT'``.
305
+ output_dimensionality: Optional `reduced dimension for the output embedding <https://ai.google.dev/api/embeddings#EmbedContentRequest>`__.
306
+ Returns:
307
+ List of embeddings, one for each text.
308
+ """
309
+ embeddings: List[List[float]] = []
310
+ batch_start_index = 0
311
+ for batch in GoogleGenerativeAIEmbeddings._prepare_batches(texts, batch_size):
312
+ if titles:
313
+ titles_batch = titles[
314
+ batch_start_index : batch_start_index + len(batch)
315
+ ]
316
+ batch_start_index += len(batch)
317
+ else:
318
+ titles_batch = [None] * len(batch) # type: ignore[list-item]
319
+
320
+ requests = [
321
+ self._prepare_request(
322
+ text=text,
323
+ task_type=task_type,
324
+ title=title,
325
+ output_dimensionality=output_dimensionality,
326
+ )
327
+ for text, title in zip(batch, titles_batch)
328
+ ]
329
+
330
+ try:
331
+ result = await self.async_client.batch_embed_contents(
332
+ BatchEmbedContentsRequest(requests=requests, model=self.model)
333
+ )
334
+ except Exception as e:
335
+ raise GoogleGenerativeAIError(f"Error embedding content: {e}") from e
336
+ embeddings.extend([list(e.values) for e in result.embeddings])
337
+ return embeddings
338
+
339
+ async def aembed_query(
340
+ self,
341
+ text: str,
342
+ *,
343
+ task_type: Optional[str] = None,
344
+ title: Optional[str] = None,
345
+ output_dimensionality: Optional[int] = None,
346
+ ) -> List[float]:
347
+ """Embed a text, using the `non-batch endpoint <https://ai.google.dev/api/embeddings#method:-models.embedcontent>`__.
348
+
349
+ Args:
350
+ text: The text to embed.
351
+ task_type: `task_type <https://ai.google.dev/api/embeddings#tasktype>`__
352
+ title: An optional title for the text.
353
+ Only applicable when TaskType is ``'RETRIEVAL_DOCUMENT'``.
354
+ output_dimensionality: Optional `reduced dimension for the output embedding <https://ai.google.dev/api/embeddings#EmbedContentRequest>`__.
355
+
356
+ Returns:
357
+ Embedding for the text.
358
+ """
359
+ task_type_to_use = task_type if task_type else self.task_type
360
+ if task_type_to_use is None:
361
+ task_type_to_use = "RETRIEVAL_QUERY"
362
+ try:
363
+ request: EmbedContentRequest = self._prepare_request(
364
+ text=text,
365
+ task_type=task_type,
366
+ title=title,
367
+ output_dimensionality=output_dimensionality,
368
+ )
369
+ result: EmbedContentResponse = await self.async_client.embed_content(
370
+ request
371
+ )
372
+ except Exception as e:
373
+ raise GoogleGenerativeAIError(f"Error embedding content: {e}") from e
374
+ return list(result.embedding.values)
@@ -63,6 +63,9 @@ class GoogleGenerativeAI(_BaseGoogleGenerativeAI, BaseLLM):
63
63
  def validate_environment(self) -> Self:
64
64
  """Validates params and passes them to google-generativeai package."""
65
65
 
66
+ if not any(self.model.startswith(prefix) for prefix in ("models/",)):
67
+ self.model = f"models/{self.model}"
68
+
66
69
  self.client = ChatGoogleGenerativeAI(
67
70
  api_key=self.google_api_key,
68
71
  credentials=self.credentials,
@@ -86,6 +89,15 @@ class GoogleGenerativeAI(_BaseGoogleGenerativeAI, BaseLLM):
86
89
  """Get standard params for tracing."""
87
90
  ls_params = super()._get_ls_params(stop=stop, **kwargs)
88
91
  ls_params["ls_provider"] = "google_genai"
92
+
93
+ models_prefix = "models/"
94
+ ls_model_name = (
95
+ self.model[len(models_prefix) :]
96
+ if self.model and self.model.startswith(models_prefix)
97
+ else self.model
98
+ )
99
+ ls_params["ls_model_name"] = ls_model_name
100
+
89
101
  if ls_max_tokens := kwargs.get("max_output_tokens", self.max_output_tokens):
90
102
  ls_params["ls_max_tokens"] = ls_max_tokens
91
103
  return ls_params
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "langchain-google-genai"
3
- version = "2.1.7"
3
+ version = "2.1.8"
4
4
  description = "An integration package connecting Google's genai package and LangChain"
5
5
  authors = []
6
6
  readme = "README.md"