Skip to main content
您当前所在页面记录的是将 Amazon Bedrock 模型用作文本补全模型的方式。Bedrock 上许多流行的模型是聊天补全模型您可能需要查看此页面
Amazon Bedrock 是一项完全托管的服务,通过单一 API 提供来自 AI21 LabsAnthropicCohereMetaStability AIAmazon 等领先 AI 公司的高性能基础模型 (FM) 选择,同时提供构建具有安全性、隐私性和负责任 AI 的生成式 AI 应用所需的广泛能力。使用 Amazon Bedrock, 您可以轻松地针对您的用例试验和评估顶级 FM,使用微调和检索增强生成RAG)等技术将其与您的数据私密定制,并构建使用企业系统和数据源执行任务的代理。由于 Amazon Bedrock 是 无服务器的,您无需管理任何基础设施,并且可以使用您已经熟悉的 AWS 服务将生成式 AI 能力安全地集成和部署到您的应用程序中。
pip install -qU langchain-aws
from langchain_aws import BedrockLLM

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

自定义模型

custom_llm = BedrockLLM(
    credentials_profile_name="bedrock-admin",
    provider="cohere",
    model_id="<Custom model ARN>",  # ARN like 'arn:aws:bedrock:...' obtained via provisioning the custom model
    model_kwargs={"temperature": 1},
    streaming=True,
)

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

Amazon Bedrock 的护栏

Amazon Bedrock 的护栏根据特定用例的策略评估用户输入和模型响应,无论底层模型如何,都提供额外的安全保障层。护栏可应用于多种模型,包括 Anthropic Claude、Meta Llama 2、Cohere Command、AI21 Labs Jurassic 和 Amazon Titan Text,以及微调后的模型。 在本节中,我们将设置一个具有特定护栏(包含追踪功能)的 Bedrock 语言模型。
from typing import Any

from langchain_core.callbacks import AsyncCallbackHandler


class BedrockAsyncCallbackHandler(AsyncCallbackHandler):
    # Async callback handler that can be used to handle callbacks from langchain.

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


# Guardrails for Amazon Bedrock with trace
llm = BedrockLLM(
    credentials_profile_name="bedrock-admin",
    model_id="<Model_ID>",
    model_kwargs={},
    guardrails={"id": "<Guardrail_ID>", "version": "<Version>", "trace": True},
    callbacks=[BedrockAsyncCallbackHandler()],
)