> ## 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.

# Bedrock 集成

> 使用 LangChain Python 与 Bedrock LLM 集成。

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

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

> [Amazon Bedrock](https://aws.amazon.com/bedrock/) 是一项完全托管的服务，它通过单一 API 提供来自 `AI21 Labs`、`Anthropic`、`Cohere`、`Meta`、`Stability AI` 和 `Amazon` 等领先 AI 公司的高性能基础模型（FMs）选择，以及构建安全、隐私和负责任 AI 的生成式 AI 应用程序所需的广泛功能集。使用 `Amazon Bedrock`，您可以轻松地为您的用例试验和评估顶级 FMs，使用微调和 `检索增强生成`（`RAG`）等技术使用您的数据对其进行私有定制，并构建使用您的企业系统和数据源执行任务的代理。由于 `Amazon Bedrock` 是无服务器的，您无需管理任何基础设施，并且可以使用您已经熟悉的 AWS 服务安全地将生成式 AI 功能集成并部署到您的应用程序中。

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

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

llm = BedrockLLM(
    credentials_profile_name="bedrock-admin", model_id="amazon.titan-text-express-v1"
)
```

### 自定义模型

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
custom_llm = BedrockLLM(
    credentials_profile_name="bedrock-admin",
    provider="cohere",
    model_id="<Custom model ARN>",  # 通过配置自定义模型获得的 ARN，如 'arn:aws:bedrock:...'
    model_kwargs={"temperature": 1},
    streaming=True,
)

custom_llm.invoke(input="What is the recipe of mayonnaise?")
```

## Amazon Bedrock 的防护栏

[Amazon Bedrock 的防护栏](https://aws.amazon.com/bedrock/guardrails/)根据特定用例的策略评估用户输入和模型响应，并提供额外的安全层，无论底层模型如何。防护栏可以应用于多种模型，包括 Anthropic Claude、Meta Llama 2、Cohere Command、AI21 Labs Jurassic 和 Amazon Titan Text，以及微调模型。
在本节中，我们将设置一个具有特定防护栏的 Bedrock 语言模型，这些防护栏包括跟踪功能。

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

from langchain_core.callbacks import AsyncCallbackHandler


class BedrockAsyncCallbackHandler(AsyncCallbackHandler):
    # 可用于处理来自 langchain 回调的异步回调处理器。

    async def on_llm_error(self, error: BaseException, **kwargs: Any) -> Any:
        reason = kwargs.get("reason")
        if reason == "GUARDRAIL_INTERVENED":
            print(f"Guardrails: {kwargs}")


# 带有跟踪功能的 Amazon Bedrock 防护栏
llm = BedrockLLM(
    credentials_profile_name="bedrock-admin",
    model_id="<Model_ID>",
    model_kwargs={},
    guardrails={"id": "<Guardrail_ID>", "version": "<Version>", "trace": True},
    callbacks=[BedrockAsyncCallbackHandler()],
)
```

***

<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/bedrock.mdx) 或 [提交问题](https://github.com/langchain-ai/docs/issues/new/choose)。
  </Callout>
</div>
