📘 **TELUS Agriculture & Consumer Goods** 如何通过 **Haystack Agents** 转变促销交易
由 deepset 维护

集成:Google Gen AI

通过新的 Google Gen AI SDK 将 Google 的 Gemini 模型与 Haystack 结合使用

作者
deepset
Gary Badwal

目录

概述

Google Gen AI 通过新的 Google Gen AI SDK 提供对 Google Gemini 模型的访问。此集成支持通过更新的 API 接口使用 Google 的最新生成模型。Google Gen AI 兼容 Gemini Developer API 和 Vertex AI API。

Haystack 支持最新的 Gemini 模型,如 gemini-2.0-flashtext-embedding-004,用于执行**聊天补全**、**函数调用**、**流式响应**和**嵌入生成**等任务。

安装

安装 Google Gen AI 集成

pip install google-genai-haystack

使用

安装后,您将可以访问 Haystack Chat 组件

  • GoogleGenAIChatGenerator:将此组件与 Gemini 模型(例如,用于聊天补全和函数调用的“gemini-2.0-flash”)结合使用。
  • GoogleGenAIDocumentEmbedder:将此组件与 Google GenAI 模型(例如,用于生成文档嵌入的“text-embedding-004”)结合使用。
  • GoogleGenAITextEmbedder:将此组件与 Google GenAI 模型(例如,用于生成文本嵌入的“text-embedding-004”)结合使用。

要将此组件与 Gemini Developer API 结合使用并获取 API 密钥,请访问 Google AI Studio。要将此组件与 Vertex AI API 结合使用,请访问 Google Cloud > Vertex AI

身份验证

以下示例展示了如何将该组件与 Gemini Developer API 和 Vertex AI API 结合使用。它们也适用于 Embedders。

Gemini Developer API(API 密钥身份验证)

from haystack_integrations.components.generators.google_genai import GoogleGenAIChatGenerator

# set the environment variable (GOOGLE_API_KEY or GEMINI_API_KEY)
chat_generator = GoogleGenAIChatGenerator()

Vertex AI(应用程序默认凭据)

from haystack_integrations.components.generators.google_genai import GoogleGenAIChatGenerator

# Using Application Default Credentials (requires gcloud auth setup)
chat_generator = GoogleGenAIChatGenerator(
    api="vertex",
    vertex_ai_project="my-project",
    vertex_ai_location="us-central1",
)

Vertex AI(API 密钥身份验证)

from haystack_integrations.components.generators.google_genai import GoogleGenAIChatGenerator

# set the environment variable (GOOGLE_API_KEY or GEMINI_API_KEY)
chat_generator = GoogleGenAIChatGenerator(api="vertex")

使用 gemini-2.0-flash 进行聊天生成

要使用 Gemini 模型进行聊天生成,请设置 GOOGLE_API_KEYGEMINI_API_KEY 环境变量,然后使用 "gemini-2.0-flash" 初始化 GoogleGenAIChatGenerator

import os
from haystack.dataclasses.chat_message import ChatMessage
from haystack_integrations.components.generators.google_genai import GoogleGenAIChatGenerator

os.environ["GOOGLE_API_KEY"] = "YOUR-GOOGLE-API-KEY"

# Initialize the chat generator
chat_generator = GoogleGenAIChatGenerator(model="gemini-2.0-flash")

# Generate a response
messages = [ChatMessage.from_user("Tell me about the future of AI")]
response = chat_generator.run(messages=messages)
print(response["replies"][0].text)

输出

The future of AI is incredibly exciting and multifaceted, with developments spanning multiple domains...

流式聊天生成

对于实时流式响应,您可以使用流式回调功能

import os
from haystack.dataclasses.chat_message import ChatMessage
from haystack.dataclasses import StreamingChunk
from haystack_integrations.components.generators.google_genai import GoogleGenAIChatGenerator

os.environ["GOOGLE_API_KEY"] = "YOUR-GOOGLE-API-KEY"

def streaming_callback(chunk: StreamingChunk):
    print(chunk.content, end='', flush=True)

# Initialize with streaming callback
chat_generator = GoogleGenAIChatGenerator(
    model="gemini-2.0-flash",
    streaming_callback=streaming_callback
)

# Generate a streaming response
messages = [ChatMessage.from_user("Write a short story about robots")]
response = chat_generator.run(messages=messages)
# Text will stream in real-time via the callback

函数调用

与 Gemini 模型聊天时,您还可以使用函数调用来进行工具集成

import os
from haystack.dataclasses.chat_message import ChatMessage
from haystack.tools import Tool

os.environ["GOOGLE_API_KEY"] = "YOUR-GOOGLE-API-KEY"

# Define a simple weather function
def get_weather(city: str) -> str:
    return f"The weather in {city} is sunny and 25°C"

# Create a tool from the function
weather_tool = Tool(
    name="get_weather",
    description="Get weather information for a city",
    parameters={
        "type": "object",
        "properties": {
            "city": {"type": "string", "description": "The city name"}
        },
        "required": ["city"]
    },
    function=get_weather
)

# Initialize chat generator with tools
chat_generator = GoogleGenAIChatGenerator(
    model="gemini-2.0-flash",
    tools=[weather_tool]
)

# Generate response with tool usage
messages = [ChatMessage.from_user("What's the weather like in Paris?")]
response = chat_generator.run(messages=messages)

# The model will call the weather function and provide a natural response
print(response["replies"][0].text)

输出

The weather in Paris is sunny and 25°C.

文档嵌入

import os
from haystack import Document
from haystack_integrations.components.embedders.google_genai import GoogleGenAIDocumentEmbedder

os.environ["GOOGLE_API_KEY"] = "YOUR-GOOGLE-API-KEY"

# Initialize the embedder
embedder = GoogleGenAIDocumentEmbedder()

# Generate a response
doc = Document(content="some text")
docs_w_embeddings = embedder.run(documents=[doc])["documents"]

文本嵌入

import os
from haystack_integrations.components.embedders.google_genai import GoogleGenAITextEmbedder

os.environ["GOOGLE_API_KEY"] = "YOUR-GOOGLE-API-KEY"

text_to_embed = "I love pizza!"

# Initialize the text embedder
text_embedder = GoogleGenAITextEmbedder()

# Generate a response
print(text_embedder.run(text_to_embed))

输出

{'embedding': [-0.052871075, -0.035282962, ...., -0.04802792], 
'meta': {'model': 'text-embedding-004'}}