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

集成:Google AI

将 Google AI 模型与 Haystack 结合使用

作者
deepset

目录

概述

🚧 此集成使用了已弃用的 SDK。

我们建议改用新的 Google GenAI 集成。

Google AI 是一个机器学习 (ML) 平台,可让您训练和部署 ML 模型和 AI 应用程序,并自定义大型语言模型 (LLM),以便在您的人工智能驱动型应用程序中使用。此集成允许通过 Google AI Studio 使用 Google 生成模型。

Haystack 支持所有可用的 多模态 Gemini 模型,用于执行文本生成、函数调用视觉问答代码生成图像字幕等任务。

安装

安装 Google AI 集成

pip install google-ai-haystack

使用

安装后,您将可以使用各种 Haystack 生成器

  • GoogleAIGeminiGenerator:将此组件与 Gemini 模型(如 'gemini-2.0-flash'、'gemini-2.5-flash'、'gemini-1.5-pro')结合使用,用于文本生成和多模态提示。
  • GoogleAIGeminiChatGenerator:将此组件与 Gemini 模型(如 'gemini-2.0-flash'、'gemini-2.5-flash' 和 'gemini-1.5-pro')结合使用,用于聊天完成场景中的文本生成和函数调用。

要使用 Google Gemini 模型,您需要一个 API 密钥。您可以将其作为初始化参数传递,或者设置一个 GOOGLE_API_KEY 环境变量。如果两者均未设置,您将无法使用生成器。

要获取 API 密钥,请访问 Google AI Studio

使用 gemini-1.5-pro 进行文本生成

要将 Gemini 模型用于文本生成,请设置 GOOGLE_API_KEY 环境变量,然后使用 "gemini-1.5-pro" 初始化 GoogleAIGeminiGenerator

import os
from haystack_integrations.components.generators.google_ai import GoogleAIGeminiGenerator

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

gemini_generator = GoogleAIGeminiGenerator(model="gemini-1.5-pro")
result = gemini_generator.run(parts = ["What is assemblage in art?"])
print(result["replies"][0])

输出

Assemblage in art refers to the creation of a three-dimensional artwork by combining various found objects...

使用 gemini-1.5-flash 实现多模态

要将 gemini-1.5-flash 模型用于视觉问答,请使用 "gemini-1.5-flash"project_id 初始化 GoogleAIGeminiGenerator。然后,运行它并传入图像以及提示。

import requests
import os
from haystack.dataclasses.byte_stream import ByteStream

from haystack_integrations.components.generators.google_ai import GoogleAIGeminiGenerator

BASE_URL = (
    "https://raw.githubusercontent.com/deepset-ai/haystack-core-integrations"
    "/main/integrations/google_ai/example_assets"
)

URLS = [
    f"{BASE_URL}/robot1.jpg",
    f"{BASE_URL}/robot2.jpg",
    f"{BASE_URL}/robot3.jpg",
    f"{BASE_URL}/robot4.jpg"
]
images = [
    ByteStream(data=requests.get(url).content, mime_type="image/jpeg")
    for url in URLS
]

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

gemini_generator = GoogleAIGeminiGenerator(model="gemini-1.5-flash")
result = gemini_generator.run(parts = ["What can you tell me about these robots?", *images])
for answer in result["replies"]:
    print(answer)

输出

The first image is of C-3PO and R2-D2 from the Star Wars franchise...
The second image is of Maria from the 1927 film Metropolis...
The third image is of Gort from the 1951 film The Day the Earth Stood Still...
The fourth image is of Marvin from the 1977 film The Hitchhiker's Guide to the Galaxy...

函数调用

与 Gemini 聊天时,我们还可以使用函数调用。

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_ai import GoogleAIGeminiChatGenerator


# 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 = GoogleAIGeminiChatGenerator(
    model="gemini-2.0-flash-exp",
    api_key=Secret.from_token("<MY_API_KEY>"),
    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)

将输出

In Berlin, the weather is sunny with a temperature of 20 degrees Celsius.

代码生成

Gemini 还可以轻松生成代码,这是一个示例

import os
from haystack_integrations.components.generators.google_ai import GoogleAIGeminiGenerator

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

gemini_generator = GoogleAIGeminiGenerator(model="gemini-1.5-pro")
result = gemini_generator.run("Write a code for calculating fibonacci numbers in JavaScript")
print(result["replies"][0])

输出

// Recursive approach
function fibonacciRecursive(n) {
  if (n <= 1) {
    return n;
  } else {
    return fibonacciRecursive(n - 1) + fibonacciRecursive(n - 2);
  }
}

// Iterative approach
function fibonacciIterative(n) {
  if (n <= 1) {
    return n;
  }

  let fibSequence = [0, 1];
  while (fibSequence.length < n + 1) {
    let nextNumber =
      fibSequence[fibSequence.length - 1] + fibSequence[fibSequence.length - 2];
    fibSequence.push(nextNumber);
  }

  return fibSequence[n];
}

// Usage
console.log(fibonacciRecursive(7)); // Output: 13
console.log(fibonacciIterative(7)); // Output: 13