> ## Documentation Index
> Fetch the complete documentation index at: https://cndoc-langchain.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Google生成式AI集成

> 开始在LangChain中使用旧版Gemini大语言模型。

<Warning>
  **您当前正在查看的是关于将Google模型用作文本补全模型的文档。许多流行的Google模型是[聊天补全模型](/oss/python/langchain/models)。**

  您可能想查看[此页面](/oss/python/integrations/chat/google_generative_ai/)。
</Warning>

一份关于如何在LangChain中使用[Google生成式AI](https://developers.generativeai.google/)模型的指南。请注意：它与Google Cloud Vertex AI [集成](/oss/python/integrations/llms/google_vertex_ai)是分开的。

## 设置

要使用Google生成式AI，您必须安装 `langchain-google-genai` Python包并生成一个API密钥。[阅读更多详情](https://developers.generativeai.google/)。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
pip install -qU  langchain-google-genai
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_google_genai import GoogleGenerativeAI
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from getpass import getpass

api_key = getpass()
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
llm = GoogleGenerativeAI(model="models/text-bison-001", google_api_key=api_key)
print(
    llm.invoke(
        "What are some of the pros and cons of Python as a programming language?"
    )
)
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
**Python的优点：**

* **易于学习：** Python是一种非常容易学习的编程语言，即使对于初学者也是如此。它的语法简单明了，并且有很多资源可以帮助您入门。
* **用途广泛：** Python可用于各种任务，包括Web开发、数据科学和机器学习。对于初学者来说也是一个不错的选择，因为它可以用于各种项目，因此您可以先学习基础知识，然后再处理更复杂的任务。
* **高级语言：** Python是一种高级编程语言，这意味着它比其他编程语言更接近人类语言。这使得它更易于阅读和理解，对于初学者来说可能是一个很大的优势。
* **开源：** Python是一种开源编程语言，这意味着它是免费使用的，并且有很多资源可以帮助您学习它。
* **社区：** Python拥有一个庞大而活跃的开发者社区，这意味着如果您遇到困难，有很多人可以帮助您。

**Python的缺点：**

* **速度慢：** 与C++等其他一些语言相比，Python是一种相对较慢的编程语言。如果您正在处理计算密集型任务，这可能是一个缺点。
* **性能不高：** Python的性能不如C++或Java等其他一些编程语言。如果您正在处理需要高性能的项目，这可能是一个缺点。
* **动态类型：** Python是一种动态类型编程语言，这意味着变量的类型可以在运行时更改。如果您需要确保代码是类型安全的，这可能是一个缺点。
* **非托管内存：** Python使用垃圾回收系统来管理内存。如果您需要对内存管理有更多控制，这可能是一个缺点。

总的来说，Python对于初学者来说是一种非常好的编程语言。它易于学习，用途广泛，并且拥有庞大的开发者社区。然而，重要的是要意识到它的局限性，例如其较慢的性能和缺乏性能。
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
llm = GoogleGenerativeAI(model="gemini-pro", google_api_key=api_key)
print(
    llm.invoke(
        "What are some of the pros and cons of Python as a programming language?"
    )
)
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
**优点：**

* **简洁性和可读性：** Python以其简单易读的语法而闻名，这使其易于初学者上手，并减少了出错的机会。它使用缩进来定义代码块，使代码结构清晰且视觉上吸引人。

* **多功能性：** Python是一种通用语言，意味着它可以用于广泛的任务，包括Web开发、数据科学、机器学习和桌面应用程序。这种多功能性使其成为各种项目和行业的热门选择。

* **庞大的社区：** Python拥有一个庞大而活跃的开发者社区，这促进了其发展和普及。该社区提供了广泛的文档、教程和开源库，使Python开发者能够轻松找到支持和资源。

* **丰富的库：** Python为各种任务提供了丰富的库和框架集合，例如数据分析（NumPy、Pandas）、Web开发（Django、Flask）、机器学习（Scikit-learn、TensorFlow）等等。这些库提供了预构建的函数和模块，使开发者能够快速高效地解决常见问题。

* **跨平台支持：** Python是跨平台的，意味着它可以在各种操作系统上运行，包括Windows、macOS和Linux。这允许开发者编写可以轻松跨不同平台共享和使用的代码。

**缺点：**

* **速度和性能：** 由于其解释型特性，Python通常比C++或Java等编译型语言慢。对于性能密集型任务，例如实时系统或繁重的数值计算，这可能是一个缺点。

* **内存使用：** 与编译型语言相比，Python程序往往消耗更多内存。这是因为Python使用动态内存分配系统，这可能导致内存碎片化和更高的内存使用率。

* **缺乏静态类型：** Python是一种动态类型语言，这意味着变量的数据类型没有显式定义。这可能使得在开发过程中检测类型错误变得具有挑战性，从而导致运行时出现意外行为或错误。

* **GIL（全局解释器锁）：** Python使用全局解释器锁（GIL）来确保一次只有一个线程可以执行Python字节码。这可能会限制Python程序的可扩展性和并行性，尤其是在多线程或多处理场景中。

* **包管理：** 虽然Python拥有庞大的库和包生态系统，但管理依赖项和包版本可能具有挑战性。Python包索引（PyPI）是Python包的官方仓库，但确保兼容性和避免不同版本包之间的冲突可能很困难。
```

## 在链中使用

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_core.prompts import PromptTemplate
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
template = """Question: {question}

Answer: Let's think step by step."""
prompt = PromptTemplate.from_template(template)

chain = prompt | llm

question = "How much is 2+2?"
print(chain.invoke({"question": question}))
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
4
```

## 流式调用

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import sys

for chunk in llm.stream("Tell me a short poem about snow"):
    sys.stdout.write(chunk)
    sys.stdout.flush()
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
In winter's embrace, a silent ballet,
Snowflakes descend, a celestial display.
Whispering secrets, they softly fall,
A blanket of white, covering all.

With gentle grace, they paint the land,
Transforming the world into a winter wonderland.
Trees stand adorned in icy splendor,
A glistening spectacle, a sight to render.

Snowflakes twirl, like dancers on a stage,
Creating a symphony, a winter montage.
Their silent whispers, a sweet serenade,
As they dance and twirl, a snowy cascade.

In the hush of dawn, a frosty morn,
Snow sparkles bright, like diamonds reborn.
Each flake unique, in its own design,
A masterpiece crafted by the divine.

So let us revel in this wintry bliss,
As snowflakes fall, with a gentle kiss.
For in their embrace, we find a peace profound,
A frozen world, with magic all around.
```

### 安全设置

Gemini模型具有默认的安全设置，可以被覆盖。如果您从模型收到大量“安全警告”，可以尝试调整模型的 `safety_settings` 属性。例如，要关闭危险内容的安全阻止，您可以按如下方式构建您的LLM：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_google_genai import GoogleGenerativeAI, HarmBlockThreshold, HarmCategory

llm = GoogleGenerativeAI(
    model="gemini-pro",
    google_api_key=api_key,
    safety_settings={
        HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT: HarmBlockThreshold.BLOCK_NONE,
    },
)
```

有关可用类别和阈值的枚举，请参阅Google的[安全设置类型](https://ai.google.dev/api/python/google/generativeai/types/SafetySettingDict)。

***

<div className="source-links">
  <Callout icon="terminal-2">
    [将这些文档](/use-these-docs)通过MCP连接到Claude、VSCode等，以获取实时答案。
  </Callout>

  <Callout icon="edit">
    [在GitHub上编辑此页面](https://github.com/langchain-ai/docs/edit/main/src/oss/python/integrations/llms/google_generative_ai.mdx)或[提交问题](https://github.com/langchain-ai/docs/issues/new/choose)。
  </Callout>
</div>
