Bedrock
Amazon Bedrock 是一项完全托管的服务,通过单一 API 提供来自
AI21 Labs、Anthropic、Cohere、Meta、Stability AI和Amazon等领先人工智能公司的多种高性能基础模型 (FM),以及您构建生成式 AI 应用所需的广泛功能,并具备安全性、隐私性和负责任的 AI。使用Amazon Bedrock,您可以轻松试验和评估适合您用例的顶级 FM,通过微调和检索增强生成(RAG) 等技术用您的数据私下定制它们,并构建使用您的企业系统和数据源执行任务的代理。由于Amazon Bedrock是无服务器的,因此您无需管理任何基础设施,并且可以使用您已经熟悉的 AWS 服务将生成式 AI 功能安全地集成和部署到您的应用程序中。
%pip install --upgrade --quiet langchain_aws
from langchain_aws import BedrockLLM
llm = BedrockLLM(
credentials_profile_name="bedrock-admin", model_id="amazon.titan-text-express-v1"
)
API Reference:BedrockLLM
自定义模型
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,以及微调模型。 注意:Amazon Bedrock 的护栏目前处于预览阶段,尚未正式发布。如果您希望获得此功能的使用权限,请通过您常用的 AWS 支持联系人联系我们。 在本节中,我们将为 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()],
)
API Reference:AsyncCallbackHandler
Related
- LLM conceptual guide
- LLM how-to guides