langchain-google-genai 1.0.2__py3-none-any.whl → 1.0.4__py3-none-any.whl

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.

@@ -1,12 +1,19 @@
1
1
  from typing import Any, Dict, List, Optional
2
2
 
3
3
  # TODO: remove ignore once the google package is published with types
4
- import google.generativeai as genai # type: ignore[import]
4
+ from google.ai.generativelanguage_v1beta.types import (
5
+ BatchEmbedContentsRequest,
6
+ EmbedContentRequest,
7
+ )
5
8
  from langchain_core.embeddings import Embeddings
6
9
  from langchain_core.pydantic_v1 import BaseModel, Field, SecretStr, root_validator
7
10
  from langchain_core.utils import get_from_dict_or_env
8
11
 
9
- from langchain_google_genai._common import GoogleGenerativeAIError
12
+ from langchain_google_genai._common import (
13
+ GoogleGenerativeAIError,
14
+ get_client_info,
15
+ )
16
+ from langchain_google_genai._genai_extension import build_generative_service
10
17
 
11
18
 
12
19
  class GoogleGenerativeAIEmbeddings(BaseModel, Embeddings):
@@ -27,6 +34,7 @@ class GoogleGenerativeAIEmbeddings(BaseModel, Embeddings):
27
34
  embeddings.embed_query("What's our Q1 revenue?")
28
35
  """
29
36
 
37
+ client: Any #: :meta private:
30
38
  model: str = Field(
31
39
  ...,
32
40
  description="The name of the embedding model to use. "
@@ -61,47 +69,52 @@ class GoogleGenerativeAIEmbeddings(BaseModel, Embeddings):
61
69
  None,
62
70
  description="A string, one of: [`rest`, `grpc`, `grpc_asyncio`].",
63
71
  )
72
+ request_options: Optional[Dict] = Field(
73
+ None,
74
+ description="A dictionary of request options to pass to the Google API client."
75
+ "Example: `{'timeout': 10}`",
76
+ )
64
77
 
65
78
  @root_validator()
66
79
  def validate_environment(cls, values: Dict) -> Dict:
67
80
  """Validates params and passes them to google-generativeai package."""
68
- if values.get("credentials"):
69
- genai.configure(
70
- credentials=values.get("credentials"),
71
- transport=values.get("transport"),
72
- client_options=values.get("client_options"),
73
- )
74
- else:
75
- google_api_key = get_from_dict_or_env(
76
- values, "google_api_key", "GOOGLE_API_KEY"
77
- )
78
- if isinstance(google_api_key, SecretStr):
79
- google_api_key = google_api_key.get_secret_value()
80
-
81
- genai.configure(
82
- api_key=google_api_key,
83
- transport=values.get("transport"),
84
- client_options=values.get("client_options"),
85
- )
81
+ google_api_key = get_from_dict_or_env(
82
+ values, "google_api_key", "GOOGLE_API_KEY"
83
+ )
84
+ client_info = get_client_info("GoogleGenerativeAIEmbeddings")
85
+
86
+ values["client"] = build_generative_service(
87
+ credentials=values.get("credentials"),
88
+ api_key=google_api_key,
89
+ client_info=client_info,
90
+ client_options=values.get("client_options"),
91
+ )
86
92
  return values
87
93
 
88
- def _embed(
89
- self, texts: List[str], task_type: str, title: Optional[str] = None
90
- ) -> List[List[float]]:
91
- task_type = self.task_type or "retrieval_document"
92
- try:
93
- result = genai.embed_content(
94
- model=self.model,
95
- content=texts,
96
- task_type=task_type,
97
- title=title,
98
- )
99
- except Exception as e:
100
- raise GoogleGenerativeAIError(f"Error embedding content: {e}") from e
101
- return result["embedding"]
94
+ def _prepare_request(
95
+ self,
96
+ text: str,
97
+ task_type: Optional[str] = None,
98
+ title: Optional[str] = None,
99
+ output_dimensionality: Optional[int] = None,
100
+ ) -> EmbedContentRequest:
101
+ task_type = self.task_type or task_type or "RETRIEVAL_DOCUMENT"
102
+ # https://ai.google.dev/api/rest/v1/models/batchEmbedContents#EmbedContentRequest
103
+ request = EmbedContentRequest(
104
+ content={"parts": [{"text": text}]},
105
+ model=self.model,
106
+ task_type=task_type.upper(),
107
+ title=title,
108
+ output_dimensionality=output_dimensionality,
109
+ )
110
+ return request
102
111
 
103
112
  def embed_documents(
104
- self, texts: List[str], batch_size: int = 5
113
+ self,
114
+ texts: List[str],
115
+ task_type: Optional[str] = None,
116
+ titles: Optional[List[str]] = None,
117
+ output_dimensionality: Optional[int] = None,
105
118
  ) -> List[List[float]]:
106
119
  """Embed a list of strings. Vertex AI currently
107
120
  sets a max batch size of 5 strings.
@@ -109,21 +122,58 @@ class GoogleGenerativeAIEmbeddings(BaseModel, Embeddings):
109
122
  Args:
110
123
  texts: List[str] The list of strings to embed.
111
124
  batch_size: [int] The batch size of embeddings to send to the model
125
+ task_type: task_type (https://ai.google.dev/api/rest/v1/TaskType)
126
+ titles: An optional list of titles for texts provided.
127
+ Only applicable when TaskType is RETRIEVAL_DOCUMENT.
128
+ output_dimensionality: Optional reduced dimension for the output embedding.
129
+ https://ai.google.dev/api/rest/v1/models/batchEmbedContents#EmbedContentRequest
112
130
 
113
131
  Returns:
114
132
  List of embeddings, one for each text.
115
133
  """
116
- task_type = self.task_type or "retrieval_document"
117
- return self._embed(texts, task_type=task_type)
134
+ titles = titles if titles else [None] * len(texts) # type: ignore[list-item]
135
+ requests = [
136
+ self._prepare_request(
137
+ text=text,
138
+ task_type=task_type,
139
+ title=title,
140
+ output_dimensionality=output_dimensionality,
141
+ )
142
+ for text, title in zip(texts, titles)
143
+ ]
118
144
 
119
- def embed_query(self, text: str) -> List[float]:
145
+ try:
146
+ result = self.client.batch_embed_contents(
147
+ BatchEmbedContentsRequest(requests=requests, model=self.model)
148
+ )
149
+ except Exception as e:
150
+ raise GoogleGenerativeAIError(f"Error embedding content: {e}") from e
151
+ return [e.values for e in result.embeddings]
152
+
153
+ def embed_query(
154
+ self,
155
+ text: str,
156
+ task_type: Optional[str] = None,
157
+ title: Optional[str] = None,
158
+ output_dimensionality: Optional[int] = None,
159
+ ) -> List[float]:
120
160
  """Embed a text.
121
161
 
122
162
  Args:
123
163
  text: The text to embed.
164
+ task_type: task_type (https://ai.google.dev/api/rest/v1/TaskType)
165
+ title: An optional title for the text.
166
+ Only applicable when TaskType is RETRIEVAL_DOCUMENT.
167
+ output_dimensionality: Optional reduced dimension for the output embedding.
168
+ https://ai.google.dev/api/rest/v1/models/batchEmbedContents#EmbedContentRequest
124
169
 
125
170
  Returns:
126
171
  Embedding for the text.
127
172
  """
128
- task_type = self.task_type or "retrieval_query"
129
- return self._embed([text], task_type=task_type)[0]
173
+ task_type = self.task_type or "RETRIEVAL_QUERY"
174
+ return self.embed_documents(
175
+ [text],
176
+ task_type=task_type,
177
+ titles=[title] if title else None,
178
+ output_dimensionality=output_dimensionality,
179
+ )[0]
@@ -86,6 +86,7 @@ def _completion_with_retry(
86
86
  stream=stream,
87
87
  generation_config=generation_config,
88
88
  safety_settings=kwargs.pop("safety_settings", None),
89
+ request_options={"timeout": llm.timeout} if llm.timeout else None,
89
90
  )
90
91
  return llm.client.generate_text(prompt=prompt, **kwargs)
91
92
  except google.api_core.exceptions.FailedPrecondition as exc:
@@ -143,6 +144,10 @@ Supported examples:
143
144
  not return the full n completions if duplicates are generated."""
144
145
  max_retries: int = 6
145
146
  """The maximum number of retries to make when generating."""
147
+
148
+ timeout: Optional[float] = None
149
+ """The maximum number of seconds to wait for a response."""
150
+
146
151
  client_options: Optional[Dict] = Field(
147
152
  None,
148
153
  description=(
@@ -169,7 +174,6 @@ Supported examples:
169
174
  from google.generativeai.types.safety_types import HarmBlockThreshold, HarmCategory
170
175
 
171
176
  safety_settings = {
172
- HarmCategory.HARM_CATEGORY_UNSPECIFIED: HarmBlockThreshold.BLOCK_NONE,
173
177
  HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT: HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE,
174
178
  HarmCategory.HARM_CATEGORY_HATE_SPEECH: HarmBlockThreshold.BLOCK_ONLY_HIGH,
175
179
  HarmCategory.HARM_CATEGORY_HARASSMENT: HarmBlockThreshold.BLOCK_LOW_AND_ABOVE,
@@ -259,6 +263,9 @@ class GoogleGenerativeAI(_BaseGoogleGenerativeAI, BaseLLM):
259
263
  if values["max_output_tokens"] is not None and values["max_output_tokens"] <= 0:
260
264
  raise ValueError("max_output_tokens must be greater than zero")
261
265
 
266
+ if values["timeout"] is not None and values["timeout"] <= 0:
267
+ raise ValueError("timeout must be greater than zero")
268
+
262
269
  return values
263
270
 
264
271
  def _generate(
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: langchain-google-genai
3
- Version: 1.0.2
3
+ Version: 1.0.4
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
@@ -12,8 +12,8 @@ Classifier: Programming Language :: Python :: 3.10
12
12
  Classifier: Programming Language :: Python :: 3.11
13
13
  Classifier: Programming Language :: Python :: 3.12
14
14
  Provides-Extra: images
15
- Requires-Dist: google-generativeai (>=0.5.0,<0.6.0)
16
- Requires-Dist: langchain-core (>=0.1.27,<0.2)
15
+ Requires-Dist: google-generativeai (>=0.5.2,<0.6.0)
16
+ Requires-Dist: langchain-core (>=0.1.45,<0.3)
17
17
  Requires-Dist: pillow (>=10.1.0,<11.0.0) ; extra == "images"
18
18
  Project-URL: Repository, https://github.com/langchain-ai/langchain-google
19
19
  Project-URL: Source Code, https://github.com/langchain-ai/langchain-google/tree/main/libs/genai
@@ -0,0 +1,16 @@
1
+ langchain_google_genai/__init__.py,sha256=Oji-S2KYWrku1wyQEskY84IOfY8MfRhujjJ4d7hbsk4,2758
2
+ langchain_google_genai/_common.py,sha256=ASlwE8hEbvOm55BVF_D4rf2nl7RYsnpsi5xbM6DW3Cc,1576
3
+ langchain_google_genai/_enums.py,sha256=KLPmxS1K83K4HjBIXFaXoL_sFEOv8Hq-2B2PDMKyDgo,197
4
+ langchain_google_genai/_function_utils.py,sha256=d0ApSCjoV9Em1CteBaGznilxrw-PDXqQ4sQa5p7cJfM,8232
5
+ langchain_google_genai/_genai_extension.py,sha256=ZwNwLV22RSf9LB7FOCLsoHzLlQDF-EQmRNYM1an2uSw,20769
6
+ langchain_google_genai/_image_utils.py,sha256=-0XgCMdYkvrIktFvUpy-2GPbFgfSVKZICawB2hiJzus,4999
7
+ langchain_google_genai/chat_models.py,sha256=3ubY5qCaZjFSHKHiiP5XCOPDusUxO8kJvpj9DwLtUG4,33014
8
+ langchain_google_genai/embeddings.py,sha256=kQW6pl1TUGKKSxiUjc7rptp0iEu_Rer1m1LLHKVaW14,6578
9
+ langchain_google_genai/genai_aqa.py,sha256=zcC5cdFYtqLK7DGPhYGvWNeHHeU-CQKA9KhewmsA5lw,4303
10
+ langchain_google_genai/google_vector_store.py,sha256=PPIk-4FmD5UUdmYA2u7VcEhGsiztvRVN59QoGLXdfoA,16139
11
+ langchain_google_genai/llms.py,sha256=S7tOy-c37DElcHtkGl8rwvvg1zOzCxb9PEyJ4E-j7qU,13431
12
+ langchain_google_genai/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
13
+ langchain_google_genai-1.0.4.dist-info/LICENSE,sha256=DppmdYJVSc1jd0aio6ptnMUn5tIHrdAhQ12SclEBfBg,1072
14
+ langchain_google_genai-1.0.4.dist-info/METADATA,sha256=nHJMXwe6iuI99J_VO1GQrVgv1BLvVGW5x0mSNswDWq0,3818
15
+ langchain_google_genai-1.0.4.dist-info/WHEEL,sha256=FMvqSimYX_P7y0a7UY-_Mc83r5zkBZsCYPm7Lr0Bsq4,88
16
+ langchain_google_genai-1.0.4.dist-info/RECORD,,
@@ -1,15 +0,0 @@
1
- langchain_google_genai/__init__.py,sha256=NiLfU4IyEQSlSl8hbN_fTdX-hrO5tuOflxFlEK0Sy4c,2762
2
- langchain_google_genai/_common.py,sha256=1r0VrrBSTZfGprmICZ5OV-W5SK31jKRFFCNE3vJ3jmk,136
3
- langchain_google_genai/_enums.py,sha256=q8IYAqufV-_yZ98FDnsZ3x-1w4804J_e8PrTKT0sdhY,163
4
- langchain_google_genai/_function_utils.py,sha256=9IVMPQq5lQB8F_whG3mrGOM_tjmP-TMEY3URHfJnjgI,3640
5
- langchain_google_genai/_genai_extension.py,sha256=2Uqg7vSF0vu1J4AhAyIPzadtpM5JJwZsBXvpItO2TY4,18736
6
- langchain_google_genai/chat_models.py,sha256=0a_bjJUSuSDVPo4AKk4bcdVhdliKchcO48y4uwYv67U,23557
7
- langchain_google_genai/embeddings.py,sha256=VbrVGX5f_aKo-XA_2lATB4GblomXYWoj9J1Cz20Pr4E,4562
8
- langchain_google_genai/genai_aqa.py,sha256=zcC5cdFYtqLK7DGPhYGvWNeHHeU-CQKA9KhewmsA5lw,4303
9
- langchain_google_genai/google_vector_store.py,sha256=PPIk-4FmD5UUdmYA2u7VcEhGsiztvRVN59QoGLXdfoA,16139
10
- langchain_google_genai/llms.py,sha256=DEz_KxEjmJafVUXtvlHccfGjMhZWnkcBei9Ey0evNgw,13193
11
- langchain_google_genai/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
12
- langchain_google_genai-1.0.2.dist-info/LICENSE,sha256=DppmdYJVSc1jd0aio6ptnMUn5tIHrdAhQ12SclEBfBg,1072
13
- langchain_google_genai-1.0.2.dist-info/METADATA,sha256=GZNA06KlCUNaISeR0xYiZrltekAa7-8sg8XIt_GwFwE,3818
14
- langchain_google_genai-1.0.2.dist-info/WHEEL,sha256=FMvqSimYX_P7y0a7UY-_Mc83r5zkBZsCYPm7Lr0Bsq4,88
15
- langchain_google_genai-1.0.2.dist-info/RECORD,,