GoogleAIGeminiGenerator
此组件允许使用 Google Gemini 模型进行文本生成。
弃用通知
此集成使用了已弃用的 google-generativeai SDK,该 SDK 将于 2025 年 8 月后停止支持。
我们建议改用新的 GoogleGenAIChatGenerator 集成。
| pipeline 中的最常见位置 | 在 PromptBuilder 之后 |
| 必需的初始化变量 | "api_key": Google AI Studio API 密钥。可以通过以下方式设置:GOOGLE_API_KEY 环境变量。 |
| 强制运行变量 | “parts”: 一个可变参数列表,包含图像、音频、视频和文本的混合,用于提示 Gemini。 |
| 输出变量 | “replies”: 一个包含模型生成的所有回复的字符串或字典列表。 |
| API 参考 | Google AI |
| GitHub 链接 | https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/google_ai |
GoogleAIGeminiGenerator 支持gemini-2.5-pro-exp-03-25, gemini-2.0-flash, gemini-1.5-pro 和gemini-1.5-flash 模型。
有关可用模型,请参阅 https://ai.google.dev/gemini-api/docs/models/gemini。
参数概述
GoogleAIGeminiGenerator 使用 Google AI Studio API 密钥进行身份验证。您可以将此密钥写入api_key 参数或GOOGLE_API_KEY 环境变量(推荐)。
如需获取 API 密钥,请访问 Google AI Studio 网站。
流式传输
此 Generator 支持将 LLM 的 token直接流式传输到输出中。要做到这一点,请将一个函数传递给streaming_callback 初始化参数。
用法
首先安装google-ai-haystack 包以使用GoogleAIGeminiGenerator:
pip install google-ai-haystack
单独使用
基本用法
import os
from haystack_integrations.components.generators.google_ai import GoogleAIGeminiGenerator
os.environ["GOOGLE_API_KEY"] = "<MY_API_KEY>"
gemini = GoogleAIGeminiGenerator(model="gemini-1.5-pro")
res = gemini.run(parts = ["What is the most interesting thing you know?"])
for answer in res["replies"]:
print(answer)
>>> 1. **The Fermi Paradox:** This paradox questions why we haven't found any signs of extraterrestrial life, despite the vastness of the universe and the high probability of life existing elsewhere.
>>> 2. **The Goldilocks Enigma:** This conundrum explores why Earth has such favorable conditions for life, despite the extreme conditions found in most of the universe. It raises questions about the rarity or commonality of Earth-like planets.
>>> 3. **The Quantum Enigma:** Quantum mechanics, the study of the behavior of matter and energy at the atomic and subatomic level, presents many counterintuitive phenomena that challenge our understanding of reality. Questions about the nature of quantum entanglement, superposition, and the origin of quantum mechanics remain unsolved.
>>> 4. **The Origin of Consciousness:** The emergence of consciousness from non-conscious matter is one of the biggest mysteries in science. How and why subjective experiences arise from physical processes in the brain remains a perplexing question.
>>> 5. **The Nature of Dark Matter and Dark Energy:** Dark matter and dark energy are mysterious substances that make up most of the universe, but their exact nature and properties are still unknown. Understanding their role in the universe's expansion and evolution is a major cosmological challenge.
>>> 6. **The Future of Artificial Intelligence:** The rapid development of Artificial Intelligence (AI) raises fundamental questions about the potential consequences and implications for society, including ethical issues, job displacement, and the long-term impact on human civilization.
>>> 7. **The Search for Life Beyond Earth:** As we continue to explore our solar system and beyond, the search for life on other planets or moons is a captivating and ongoing endeavor. Discovering extraterrestrial life would have profound implications for our understanding of the universe and our place in it.
>>> 8. **Time Travel:** The concept of time travel, whether forward or backward, remains a theoretical possibility that challenges our understanding of causality and the laws of physics. The implications and paradoxes associated with time travel have fascinated scientists and philosophers alike.
>>> 9. **The Multiverse Theory:** The multiverse theory suggests the existence of multiple universes, each with its own set of physical laws and properties. This idea raises questions about the nature of reality, the role of chance and necessity, and the possibility of parallel universes.
>>> 10. **The Fate of the Universe:** The ultimate fate of the universe is a subject of ongoing debate among cosmologists. Various theories, such as the Big Crunch, the Big Freeze, or the Big Rip, attempt to explain how the universe will end or evolve over time. Understanding the universe's destiny is a profound and awe-inspiring pursuit.
这是一个更高级的用法,同时使用文本和图像作为输入。
import requests
import os
from haystack.dataclasses.byte_stream import ByteStream
from haystack_integrations.components.generators.google_ai import GoogleAIGeminiGenerator
URLS = [
"https://raw.githubusercontent.com/silvanocerza/robots/main/robot1.jpg",
"https://raw.githubusercontent.com/silvanocerza/robots/main/robot2.jpg",
"https://raw.githubusercontent.com/silvanocerza/robots/main/robot3.jpg",
"https://raw.githubusercontent.com/silvanocerza/robots/main/robot4.jpg"
]
images = [
ByteStream(data=requests.get(url).content, mime_type="image/jpeg")
for url in URLS
]
os.environ["GOOGLE_API_KEY"] = "<MY_API_KEY>"
gemini = GoogleAIGeminiGenerator(model="gemini-1.5-pro")
result = gemini.run(parts = ["What can you tell me about this robots?", *images])
for answer in result["replies"]:
print(answer)
>>> The first image is of C-3PO and R2-D2 from the Star Wars franchise. C-3PO is a protocol droid, while R2-D2 is an astromech droid. They are both loyal companions to the heroes of the Star Wars saga.
>>> The second image is of Maria from the 1927 film Metropolis. Maria is a robot who is created to be the perfect woman. She is beautiful, intelligent, and obedient. However, she is also soulless and lacks any real emotions.
>>> The third image is of Gort from the 1951 film The Day the Earth Stood Still. Gort is a robot who is sent to Earth to warn humanity about the dangers of nuclear war. He is a powerful and intelligent robot, but he is also compassionate and understanding.
>>> The fourth image is of Marvin from the 1977 film The Hitchhiker's Guide to the Galaxy. Marvin is a robot who is depressed and pessimistic. He is constantly complaining about everything, but he is also very intelligent and has a dry sense of humor.
在 pipeline 中
在 RAG 管道中
import os
from haystack.components.retrievers.in_memory import InMemoryBM25Retriever
from haystack.components.builders import PromptBuilder
from haystack import Pipeline
from haystack.document_stores.in_memory import InMemoryDocumentStore
from haystack_integrations.components.generators.google_ai import GoogleAIGeminiGenerator
os.environ["GOOGLE_API_KEY"] = "<MY_API_KEY>"
docstore = InMemoryDocumentStore()
template = """
Given the following information, answer the question.
Context:
{% for document in documents %}
{{ document.content }}
{% endfor %}
Question: What's the official language of {{ country }}?
"""
pipe = Pipeline()
pipe.add_component("retriever", InMemoryBM25Retriever(document_store=docstore))
pipe.add_component("prompt_builder", PromptBuilder(template=template))
pipe.add_component("gemini", GoogleAIGeminiGenerator(model="gemini-pro"))
pipe.connect("retriever", "prompt_builder.documents")
pipe.connect("prompt_builder", "gemini")
pipe.run({
"prompt_builder": {
"country": "France"
}
})
更新于 5 个月前
