文档API 参考📓 教程🧑‍🍳 食谱🤝 集成💜 Discord🎨 Studio
API 参考

Google Vertex

Haystack 的 Google Vertex 集成

模块 haystack_integrations.components.generators.google_vertex.gemini

VertexAIGeminiGenerator

VertexAIGeminiGenerator 支持使用 Google Gemini 模型进行文本生成。

使用示例

from haystack_integrations.components.generators.google_vertex import VertexAIGeminiGenerator


gemini = VertexAIGeminiGenerator()
result = gemini.run(parts = ["What is the most interesting thing you know?"])
for answer in result["replies"]:
    print(answer)

>>> 1. **The Origin of Life:** How and where did life begin? The answers to this ...
>>> 2. **The Unseen Universe:** The vast majority of the universe is ...
>>> 3. **Quantum Entanglement:** This eerie phenomenon in quantum mechanics allows ...
>>> 4. **Time Dilation:** Einstein's theory of relativity revealed that time can ...
>>> 5. **The Fermi Paradox:** Despite the vastness of the universe and the ...
>>> 6. **Biological Evolution:** The idea that life evolves over time through natural ...
>>> 7. **Neuroplasticity:** The brain's ability to adapt and change throughout life, ...
>>> 8. **The Goldilocks Zone:** The concept of the habitable zone, or the Goldilocks zone, ...
>>> 9. **String Theory:** This theoretical framework in physics aims to unify all ...
>>> 10. **Consciousness:** The nature of human consciousness and how it arises ...

VertexAIGeminiGenerator.__init__

def __init__(*,
             model: str = "gemini-2.0-flash",
             project_id: Optional[str] = None,
             location: Optional[str] = None,
             generation_config: Optional[Union[GenerationConfig,
                                               Dict[str, Any]]] = None,
             safety_settings: Optional[Dict[HarmCategory,
                                            HarmBlockThreshold]] = None,
             system_instruction: Optional[Union[str, ByteStream, Part]] = None,
             streaming_callback: Optional[Callable[[StreamingChunk],
                                                   None]] = None)

使用 Google Vertex AI 通过 Gemini 模型实现的多模态生成器。

使用 Google Cloud 应用程序默认凭据 (ADC) 进行身份验证。有关更多信息,请参阅官方 Google 文档

参数:

  • project_id:要使用的 GCP 项目的 ID。默认情况下,它在 Google Cloud 身份验证期间设置。
  • model:要使用的模型的名称。有关可用模型,请参阅 https://cloud.google.com/vertex-ai/generative-ai/docs/learn/models
  • location:在进行 API 调用时要使用的默认位置,如果未设置,则使用 us-central-1。
  • generation_config:要使用的生成配置。可以是 GenerationConfig 对象或参数字典。接受的字段包括: - temperature - top_p - top_k - candidate_count - max_output_tokens - stop_sequences
  • safety_settings:要使用的安全设置。有关更多详细信息,请参阅 HarmBlockThresholdHarmCategory 的文档。
  • system_instruction:用于生成内容的默认系统指令。
  • streaming_callback: 当从流中接收到新 token 时调用的回调函数。回调函数接受 StreamingChunk 作为参数。

VertexAIGeminiGenerator.to_dict

def to_dict() -> Dict[str, Any]

将组件序列化为字典。

返回值:

包含序列化数据的字典。

VertexAIGeminiGenerator.from_dict

@classmethod
def from_dict(cls, data: Dict[str, Any]) -> "VertexAIGeminiGenerator"

从字典反序列化组件。

参数:

  • data: 要反序列化的字典。

返回值:

反序列化后的组件。

VertexAIGeminiGenerator.run

@component.output_types(replies=List[str])
def run(parts: Variadic[Union[str, ByteStream, Part]],
        streaming_callback: Optional[Callable[[StreamingChunk], None]] = None)

使用 Gemini 模型生成内容。

参数:

  • parts:模型的提示。
  • streaming_callback: 当从流中接收到新 token 时调用的回调函数。

返回值:

包含以下键的字典

  • replies:一组生成的内容。

模块 haystack_integrations.components.generators.google_vertex.captioner

VertexAIImageCaptioner

VertexAIImageCaptioner 支持使用 Google Vertex AI imagetext 生成模型进行文本生成。

使用 Google Cloud 应用程序默认凭据 (ADC) 进行身份验证。有关更多信息,请参阅官方 Google 文档

使用示例

import requests

from haystack.dataclasses.byte_stream import ByteStream
from haystack_integrations.components.generators.google_vertex import VertexAIImageCaptioner

captioner = VertexAIImageCaptioner()

image = ByteStream(
    data=requests.get(
        "https://raw.githubusercontent.com/deepset-ai/haystack-core-integrations/main/integrations/google_vertex/example_assets/robot1.jpg"
    ).content
)
result = captioner.run(image=image)

for caption in result["captions"]:
    print(caption)

>>> two gold robots are standing next to each other in the desert

VertexAIImageCaptioner.__init__

def __init__(*,
             model: str = "imagetext",
             project_id: Optional[str] = None,
             location: Optional[str] = None,
             **kwargs)

使用 Google Vertex AI 模型生成图像标题。

使用 Google Cloud 应用程序默认凭据 (ADC) 进行身份验证。有关更多信息,请参阅官方 Google 文档

参数:

  • project_id:要使用的 GCP 项目的 ID。默认情况下,它在 Google Cloud 身份验证期间设置。
  • model:要使用的模型的名称。
  • location:在进行 API 调用时要使用的默认位置,如果未设置,则使用 us-central-1。默认为 None。
  • kwargs:要传递给模型的其他关键字参数。有关支持的参数列表,请参阅ImageTextModel.get_captions() 文档。

VertexAIImageCaptioner.to_dict

def to_dict() -> Dict[str, Any]

将组件序列化为字典。

返回值:

包含序列化数据的字典。

VertexAIImageCaptioner.from_dict

@classmethod
def from_dict(cls, data: Dict[str, Any]) -> "VertexAIImageCaptioner"

从字典反序列化组件。

参数:

  • data: 要反序列化的字典。

返回值:

反序列化后的组件。

VertexAIImageCaptioner.run

@component.output_types(captions=List[str])
def run(image: ByteStream)

提示模型为给定图像生成标题。

参数:

  • image:要生成标题的图像。

返回值:

包含以下键的字典

  • captions:模型生成的标题列表。

模块 haystack_integrations.components.generators.google_vertex.code_generator

VertexAICodeGenerator

此组件支持使用 Google Vertex AI 生成模型进行代码生成。

VertexAICodeGenerator 支持code-bison, code-bison-32kcode-gecko.

使用示例

    from haystack_integrations.components.generators.google_vertex import VertexAICodeGenerator

    generator = VertexAICodeGenerator()

    result = generator.run(prefix="def to_json(data):")

    for answer in result["replies"]:
        print(answer)

    >>> ```python
    >>> import json
    >>>
    >>> def to_json(data):
    >>>   """Converts a Python object to a JSON string.
    >>>
    >>>   Args:
    >>>     data: The Python object to convert.
    >>>
    >>>   Returns:
    >>>     A JSON string representing the Python object.
    >>>   """
    >>>
    >>>   return json.dumps(data)
    >>> ```

VertexAICodeGenerator.__init__

def __init__(*,
             model: str = "code-bison",
             project_id: Optional[str] = None,
             location: Optional[str] = None,
             **kwargs)

使用 Google Vertex AI 模型生成代码。

使用 Google Cloud 应用程序默认凭据 (ADC) 进行身份验证。有关更多信息,请参阅官方 Google 文档

参数:

  • project_id:要使用的 GCP 项目的 ID。默认情况下,它在 Google Cloud 身份验证期间设置。
  • model:要使用的模型的名称。
  • location:在进行 API 调用时要使用的默认位置,如果未设置,则使用 us-central-1。
  • kwargs:要传递给模型的其他关键字参数。有关支持的参数列表,请参阅TextGenerationModel.predict() 文档。

VertexAICodeGenerator.to_dict

def to_dict() -> Dict[str, Any]

将组件序列化为字典。

返回值:

包含序列化数据的字典。

VertexAICodeGenerator.from_dict

@classmethod
def from_dict(cls, data: Dict[str, Any]) -> "VertexAICodeGenerator"

从字典反序列化组件。

参数:

  • data: 要反序列化的字典。

返回值:

反序列化后的组件。

VertexAICodeGenerator.run

@component.output_types(replies=List[str])
def run(prefix: str, suffix: Optional[str] = None)

使用 Google Vertex AI 模型生成代码。

参数:

  • prefix:当前点之前的代码。
  • suffix:当前点之后代码。

返回值:

包含以下键的字典

  • replies:一组生成的代码片段。

模块 haystack_integrations.components.generators.google_vertex.image_generator

VertexAIImageGenerator

此组件支持使用 Google Vertex AI 生成模型进行图像生成。

使用 Google Cloud 应用程序默认凭据 (ADC) 进行身份验证。有关更多信息,请参阅官方 Google 文档

使用示例

from pathlib import Path

from haystack_integrations.components.generators.google_vertex import VertexAIImageGenerator

generator = VertexAIImageGenerator()
result = generator.run(prompt="Generate an image of a cute cat")
result["images"][0].to_file(Path("my_image.png"))

VertexAIImageGenerator.__init__

def __init__(*,
             model: str = "imagegeneration",
             project_id: Optional[str] = None,
             location: Optional[str] = None,
             **kwargs)

使用 Google Vertex AI 模型生成图像。

使用 Google Cloud 应用程序默认凭据 (ADC) 进行身份验证。有关更多信息,请参阅官方 Google 文档

参数:

  • project_id:要使用的 GCP 项目的 ID。默认情况下,它在 Google Cloud 身份验证期间设置。
  • model:要使用的模型的名称。
  • location:在进行 API 调用时要使用的默认位置,如果未设置,则使用 us-central-1。
  • kwargs:要传递给模型的其他关键字参数。有关支持的参数列表,请参阅ImageGenerationModel.generate_images() 文档。

VertexAIImageGenerator.to_dict

def to_dict() -> Dict[str, Any]

将组件序列化为字典。

返回值:

包含序列化数据的字典。

VertexAIImageGenerator.from_dict

@classmethod
def from_dict(cls, data: Dict[str, Any]) -> "VertexAIImageGenerator"

从字典反序列化组件。

参数:

  • data: 要反序列化的字典。

返回值:

反序列化后的组件。

VertexAIImageGenerator.run

@component.output_types(images=List[ByteStream])
def run(prompt: str, negative_prompt: Optional[str] = None)

根据给定的提示生成图像。

参数:

  • prompt:用于生成图像的提示。
  • negative_prompt:描述您希望在生成的图像中省略的内容。

返回值:

包含以下键的字典

  • images:一个 ByteStream 对象列表,每个对象都包含一个图像。

模块 haystack_integrations.components.generators.google_vertex.question_answering

VertexAIImageQA

此组件支持使用 Google Vertex AI 生成模型进行文本生成(图像标题生成)。

使用 Google Cloud 应用程序默认凭据 (ADC) 进行身份验证。有关更多信息,请参阅官方 Google 文档

使用示例

from haystack.dataclasses.byte_stream import ByteStream
from haystack_integrations.components.generators.google_vertex import VertexAIImageQA

qa = VertexAIImageQA()

image = ByteStream.from_file_path("dog.jpg")

res = qa.run(image=image, question="What color is this dog")

print(res["replies"][0])

>>> white

VertexAIImageQA.__init__

def __init__(*,
             model: str = "imagetext",
             project_id: Optional[str] = None,
             location: Optional[str] = None,
             **kwargs)

使用 Google Vertex AI 模型回答有关图像的问题。

使用 Google Cloud 应用程序默认凭据 (ADC) 进行身份验证。有关更多信息,请参阅官方 Google 文档

参数:

  • project_id:要使用的 GCP 项目的 ID。默认情况下,它在 Google Cloud 身份验证期间设置。
  • model:要使用的模型的名称。
  • location:在进行 API 调用时要使用的默认位置,如果未设置,则使用 us-central-1。
  • kwargs:要传递给模型的其他关键字参数。有关支持的参数列表,请参阅ImageTextModel.ask_question() 文档。

VertexAIImageQA.to_dict

def to_dict() -> Dict[str, Any]

将组件序列化为字典。

返回值:

包含序列化数据的字典。

VertexAIImageQA.from_dict

@classmethod
def from_dict(cls, data: Dict[str, Any]) -> "VertexAIImageQA"

从字典反序列化组件。

参数:

  • data: 要反序列化的字典。

返回值:

反序列化后的组件。

VertexAIImageQA.run

@component.output_types(replies=List[str])
def run(image: ByteStream, question: str)

提示模型回答有关图像的问题。

参数:

  • image:要提问的图像。
  • question:要问的问题。

返回值:

包含以下键的字典

  • replies:一组问题的答案。

模块 haystack_integrations.components.generators.google_vertex.text_generator

VertexAITextGenerator

此组件支持使用 Google Vertex AI 生成模型进行文本生成。

VertexAITextGenerator 支持text-bison, text-unicorntext-bison-32k 模型。

使用 Google Cloud 应用程序默认凭据 (ADC) 进行身份验证。有关更多信息,请参阅官方 Google 文档

使用示例

    from haystack_integrations.components.generators.google_vertex import VertexAITextGenerator

    generator = VertexAITextGenerator()
    res = generator.run("Tell me a good interview question for a software engineer.")

    print(res["replies"][0])

    >>> **Question:**
    >>> You are given a list of integers and a target sum.
    >>> Find all unique combinations of numbers in the list that add up to the target sum.
    >>>
    >>> **Example:**
    >>>
    >>> ```
    >>> Input: [1, 2, 3, 4, 5], target = 7
    >>> Output: [[1, 2, 4], [3, 4]]
    >>> ```
    >>>
    >>> **Follow-up:** What if the list contains duplicate numbers?

VertexAITextGenerator.__init__

def __init__(*,
             model: str = "text-bison",
             project_id: Optional[str] = None,
             location: Optional[str] = None,
             **kwargs)

使用 Google Vertex AI 模型生成文本。

使用 Google Cloud 应用程序默认凭据 (ADC) 进行身份验证。有关更多信息,请参阅官方 Google 文档

参数:

  • project_id:要使用的 GCP 项目的 ID。默认情况下,它在 Google Cloud 身份验证期间设置。
  • model:要使用的模型的名称。
  • location:在进行 API 调用时要使用的默认位置,如果未设置,则使用 us-central-1。
  • kwargs:要传递给模型的其他关键字参数。有关支持的参数列表,请参阅TextGenerationModel.predict() 文档。

VertexAITextGenerator.to_dict

def to_dict() -> Dict[str, Any]

将组件序列化为字典。

返回值:

包含序列化数据的字典。

VertexAITextGenerator.from_dict

@classmethod
def from_dict(cls, data: Dict[str, Any]) -> "VertexAITextGenerator"

从字典反序列化组件。

参数:

  • data: 要反序列化的字典。

返回值:

反序列化后的组件。

VertexAITextGenerator.run

@component.output_types(replies=List[str],
                        safety_attributes=Dict[str, float],
                        citations=List[Dict[str, Any]])
def run(prompt: str)

提示模型生成文本。

参数:

  • prompt:用于文本生成的提示。

返回值:

包含以下键的字典

  • replies:一组生成的回复。
  • safety_attributes:包含每个答案的安全分数的字典。
  • citations:每个答案的引用列表。

模块 haystack_integrations.components.generators.google_vertex.chat.gemini

VertexAIGeminiChatGenerator

VertexAIGeminiChatGenerator 支持使用 Google Gemini 模型进行聊天补全。

使用 Google Cloud 应用程序默认凭据 (ADC) 进行身份验证。有关更多信息,请参阅官方 Google 文档

使用示例

from haystack.dataclasses import ChatMessage
from haystack_integrations.components.generators.google_vertex import VertexAIGeminiChatGenerator

gemini_chat = VertexAIGeminiChatGenerator()

messages = [ChatMessage.from_user("Tell me the name of a movie")]
res = gemini_chat.run(messages)

print(res["replies"][0].text)
>>> The Shawshank Redemption

#### With Tool calling:

```python
from typing import Annotated
from haystack.utils import Secret
from haystack.dataclasses.chat_message import ChatMessage
from haystack.components.tools import ToolInvoker
from haystack.tools import create_tool_from_function

from haystack_integrations.components.generators.google_vertex import VertexAIGeminiChatGenerator

__example function to get the current weather__

def get_current_weather(
    location: Annotated[str, "The city for which to get the weather, e.g. 'San Francisco'"] = "Munich",
    unit: Annotated[str, "The unit for the temperature, e.g. 'celsius'"] = "celsius",
) -> str:
    return f"The weather in {location} is sunny. The temperature is 20 {unit}."

tool = create_tool_from_function(get_current_weather)
tool_invoker = ToolInvoker(tools=[tool])

gemini_chat = VertexAIGeminiChatGenerator(
    model="gemini-2.0-flash-exp",
    tools=[tool],
)
user_message = [ChatMessage.from_user("What is the temperature in celsius in Berlin?")]
replies = gemini_chat.run(messages=user_message)["replies"]
print(replies[0].tool_calls)

__actually invoke the tool__

tool_messages = tool_invoker.run(messages=replies)["tool_messages"]
messages = user_message + replies + tool_messages

__transform the tool call result into a human readable message__

final_replies = gemini_chat.run(messages=messages)["replies"]
print(final_replies[0].text)

VertexAIGeminiChatGenerator.__init__

def __init__(*,
             model: str = "gemini-1.5-flash",
             project_id: Optional[str] = None,
             location: Optional[str] = None,
             generation_config: Optional[Union[GenerationConfig,
                                               Dict[str, Any]]] = None,
             safety_settings: Optional[Dict[HarmCategory,
                                            HarmBlockThreshold]] = None,
             tools: Optional[List[Tool]] = None,
             tool_config: Optional[ToolConfig] = None,
             streaming_callback: Optional[StreamingCallbackT] = None)

VertexAIGeminiChatGenerator 支持使用 Google Gemini 模型进行聊天补全。

使用 Google Cloud 应用程序默认凭据 (ADC) 进行身份验证。有关更多信息,请参阅官方 Google 文档

参数:

VertexAIGeminiChatGenerator.to_dict

def to_dict() -> Dict[str, Any]

将组件序列化为字典。

返回值:

包含序列化数据的字典。

VertexAIGeminiChatGenerator.from_dict

@classmethod
def from_dict(cls, data: Dict[str, Any]) -> "VertexAIGeminiChatGenerator"

从字典反序列化组件。

参数:

  • data: 要反序列化的字典。

返回值:

反序列化后的组件。

VertexAIGeminiChatGenerator.run

@component.output_types(replies=List[ChatMessage])
def run(messages: List[ChatMessage],
        streaming_callback: Optional[StreamingCallbackT] = None,
        *,
        tools: Optional[List[Tool]] = None)

参数:

  • messages:一组ChatMessage 实例,表示输入消息。
  • streaming_callback: 当从流中接收到新 token 时调用的回调函数。
  • tools:模型可以准备调用的工具列表。如果设置,它将覆盖tools 参数。

返回值:

包含以下键的字典

  • replies:一个列表,包含生成的响应,形式为ChatMessage 实例。

VertexAIGeminiChatGenerator.run_async

@component.output_types(replies=List[ChatMessage])
async def run_async(messages: List[ChatMessage],
                    streaming_callback: Optional[StreamingCallbackT] = None,
                    *,
                    tools: Optional[List[Tool]] = None)

run 方法的异步版本。根据提供的消息生成文本。

参数:

  • messages:一组ChatMessage 实例,表示输入消息。
  • streaming_callback: 当从流中接收到新 token 时调用的回调函数。
  • tools:模型可以准备调用的工具列表。如果设置,它将覆盖tools 参数。

返回值:

包含以下键的字典

  • replies:一个列表,包含生成的响应,形式为ChatMessage 实例。

模块 haystack_integrations.components.embedders.google_vertex.document_embedder

VertexAIDocumentEmbedder

使用 Vertex AI Embeddings API 嵌入文本。

请参阅官方 Google 文档中提供的模型。

使用示例

from haystack import Document
from haystack_integrations.components.embedders.google_vertex import VertexAIDocumentEmbedder

doc = Document(content="I love pizza!")

document_embedder = VertexAIDocumentEmbedder(model="text-embedding-005")

result = document_embedder.run([doc])
print(result['documents'][0].embedding)
# [-0.044606007635593414, 0.02857724390923977, -0.03549133986234665,

VertexAIDocumentEmbedder.__init__

def __init__(model: Literal[
    "text-embedding-004",
    "text-embedding-005",
    "textembedding-gecko-multilingual@001",
    "text-multilingual-embedding-002",
    "text-embedding-large-exp-03-07",
],
             task_type: Literal[
                 "RETRIEVAL_DOCUMENT",
                 "RETRIEVAL_QUERY",
                 "SEMANTIC_SIMILARITY",
                 "CLASSIFICATION",
                 "CLUSTERING",
                 "QUESTION_ANSWERING",
                 "FACT_VERIFICATION",
                 "CODE_RETRIEVAL_QUERY",
             ] = "RETRIEVAL_DOCUMENT",
             gcp_region_name: Optional[Secret] = Secret.from_env_var(
                 "GCP_DEFAULT_REGION", strict=False),
             gcp_project_id: Optional[Secret] = Secret.from_env_var(
                 "GCP_PROJECT_ID", strict=False),
             batch_size: int = 32,
             max_tokens_total: int = 20000,
             time_sleep: int = 30,
             retries: int = 3,
             progress_bar: bool = True,
             truncate_dim: Optional[int] = None,
             meta_fields_to_embed: Optional[List[str]] = None,
             embedding_separator: str = "\n") -> None

使用 Google Vertex AI 模型生成 Document Embedder。

使用 Google Cloud 应用程序默认凭据 (ADC) 进行身份验证。有关更多信息,请参阅官方 Google 文档

参数:

  • model:要使用的模型的名称。
  • task_type:正在生成嵌入的任务类型。有关更多信息,请参阅官方 Google 文档
  • gcp_region_name:在进行 API 调用时要使用的默认位置,如果未设置,则使用 us-central-1。
  • gcp_project_id:要使用的 GCP 项目的 ID。默认情况下,它在 Google Cloud 身份验证期间设置。
  • batch_size:在单个批次中要处理的文档数量。
  • max_tokens_total:要处理的总最大令牌数。
  • time_sleep:重试之间的睡眠时间(秒)。
  • retries:失败时重试的次数。
  • progress_bar:在处理期间是否显示进度条。
  • truncate_dim:如果指定,则用于截断嵌入的维度。
  • meta_fields_to_embed:要包含在嵌入中的元数据字段列表。
  • embedding_separator:用于分隔不同嵌入的字符串。

引发:

  • ValueError:如果提供的模型不在支持的模型列表中。

VertexAIDocumentEmbedder.get_text_embedding_input

def get_text_embedding_input(
        batch: List[Document]) -> List[TextEmbeddingInput]

将一批 Document 对象转换为 TextEmbeddingInput 对象列表。

参数:

  • batch List[Document] - 要转换的 Document 对象列表。

返回值:

  • List[TextEmbeddingInput] - 从输入文档创建的 TextEmbeddingInput 对象列表。

VertexAIDocumentEmbedder.embed_batch_by_smaller_batches

def embed_batch_by_smaller_batches(batch: List[str],
                                   subbatch=1) -> List[List[float]]

通过将文本字符串划分为更小的子批次来嵌入一批文本字符串。

参数:

  • batch List[str] - 要嵌入的文本字符串列表。
  • subbatch int, optional - 更小的子批次的数量。默认为 1。

返回值:

  • List[List[float]] - 嵌入列表,其中每个嵌入都是一个浮点数列表。

引发:

  • Exception - 如果嵌入在项目级别失败,将抛出带有错误详细信息的异常。

VertexAIDocumentEmbedder.embed_batch

def embed_batch(batch: List[str]) -> List[List[float]]

为一批文本字符串生成嵌入。

参数:

  • batch List[str] - 要嵌入的文本字符串列表。

返回值:

  • List[List[float]] - 嵌入列表,其中每个嵌入都是一个浮点数列表。

VertexAIDocumentEmbedder.run

@component.output_types(documents=List[Document])
def run(documents: List[Document])

在坚持 API 的每个请求的令牌限制的同时,分批处理所有文档。

参数:

  • documents:要嵌入的文档列表。

返回值:

包含以下键的字典

  • documents:带有嵌入的文档列表。

VertexAIDocumentEmbedder.to_dict

def to_dict() -> Dict[str, Any]

将组件序列化为字典。

返回值:

包含序列化数据的字典。

VertexAIDocumentEmbedder.from_dict

@classmethod
def from_dict(cls, data: Dict[str, Any]) -> "VertexAIDocumentEmbedder"

从字典反序列化组件。

参数:

  • data: 要反序列化的字典。

返回值:

反序列化后的组件。

模块 haystack_integrations.components.embedders.google_vertex.text_embedder

VertexAITextEmbedder

使用 VertexAI Text Embeddings API 嵌入文本。

请参阅官方 Google 文档中提供的模型。

使用示例

from haystack_integrations.components.embedders.google_vertex import VertexAITextEmbedder

text_to_embed = "I love pizza!"

text_embedder = VertexAITextEmbedder(model="text-embedding-005")

print(text_embedder.run(text_to_embed))
# {'embedding': [-0.08127457648515701, 0.03399784862995148, -0.05116401985287666, ...]

VertexAITextEmbedder.__init__

def __init__(model: Literal[
    "text-embedding-004",
    "text-embedding-005",
    "textembedding-gecko-multilingual@001",
    "text-multilingual-embedding-002",
    "text-embedding-large-exp-03-07",
],
             task_type: Literal[
                 "RETRIEVAL_DOCUMENT",
                 "RETRIEVAL_QUERY",
                 "SEMANTIC_SIMILARITY",
                 "CLASSIFICATION",
                 "CLUSTERING",
                 "QUESTION_ANSWERING",
                 "FACT_VERIFICATION",
                 "CODE_RETRIEVAL_QUERY",
             ] = "RETRIEVAL_QUERY",
             gcp_region_name: Optional[Secret] = Secret.from_env_var(
                 "GCP_DEFAULT_REGION", strict=False),
             gcp_project_id: Optional[Secret] = Secret.from_env_var(
                 "GCP_PROJECT_ID", strict=False),
             progress_bar: bool = True,
             truncate_dim: Optional[int] = None) -> None

使用指定的模型、任务类型和 GCP 配置初始化 TextEmbedder。

参数:

  • model:要使用的模型的名称。
  • task_type:正在生成嵌入的任务类型。有关更多信息,请参阅官方 Google 文档
  • gcp_region_name:在进行 API 调用时要使用的默认位置,如果未设置,则使用 us-central-1。
  • gcp_project_id:要使用的 GCP 项目的 ID。默认情况下,它在 Google Cloud 身份验证期间设置。
  • progress_bar:在处理期间是否显示进度条。
  • truncate_dim:如果指定,则用于截断嵌入的维度。

VertexAITextEmbedder.run

@component.output_types(embedding=List[float])
def run(text: Union[List[Document], List[str], str])

在坚持 API 的每个请求的令牌限制的同时,分批处理文本。

参数:

  • text: The text to embed.

返回值:

包含以下键的字典

  • embedding:输入文本的嵌入。

VertexAITextEmbedder.to_dict

def to_dict() -> Dict[str, Any]

将组件序列化为字典。

返回值:

包含序列化数据的字典。

VertexAITextEmbedder.from_dict

@classmethod
def from_dict(cls, data: Dict[str, Any]) -> "VertexAITextEmbedder"

从字典反序列化组件。

参数:

  • data: 要反序列化的字典。

返回值:

反序列化后的组件。