跳转到主要内容
Chinese, Simplified

category

随着生成式人工智能(AI)的快速增长,许多AWS客户正在寻求利用公开可用的基础模型(FM)和技术。这包括Meta Llama 3,Meta公开的大型语言模型(LLM)。Meta和亚马逊之间的合作关系意味着集体生成人工智能创新,Meta和亚马逊正在共同努力,突破可能的界限。

在这篇文章中,我们概述了撰写本文时AWS上可用的Meta Llama 3模型,并分享了使用Meta Llama 3模型开发文本到SQL用例的最佳实践。本文中使用的所有代码都可以在附带的Github存储库中公开获得。

Meta Llama 3的背景


Meta Llama 3是Meta Llama 2的继任者,它保持了700亿个参数的容量,但通过增强的训练技术而不是纯粹的模型尺寸实现了卓越的性能。这种方法强调了Meta优化数据利用率的策略和方法,以进一步推动人工智能能力。该版本包括基于Meta Llama 2架构的新模型,有80亿和700亿个参数变体,每个变体都提供基础和指令版本。这种细分使Meta能够提供适合不同硬件和应用需求的多功能解决方案。

Meta Llama 3的一个重大升级是采用了具有128256个令牌词汇表的令牌化器,提高了多语言任务的文本编码效率。80亿参数模型集成了分组查询注意力(GQA),以改进对较长数据序列的处理,提高实际应用程序的性能。训练涉及两个GPU集群中超过15万亿个令牌的数据集,远远超过Meta Llama 2。Meta Llama 3 Instruct针对对话应用程序进行了优化,使用近端策略优化和监督微调等先进技术对1000多万个人类注释样本进行了微调。Meta Llama 3模型是许可的,允许重新分发、微调和衍生作品创作,现在需要明确的归属。此次许可更新反映了Meta致力于以透明和问责的方式促进人工智能开发中的创新和合作。

Meta Llama 3的快速工程最佳实践


以下是Meta Llama 3快速工程的最佳实践:

  • 基础模型使用——基础模型提供以下功能:
    • 无提示灵活性–Meta Llama 3中的基本模型擅长连续序列和处理零样本或少速任务,而不需要特定的提示格式。它们是适用于广泛应用的多功能工具,为进一步的微调提供了坚实的基础。
  • 指令版本-指令版本提供以下功能:
    • 结构化对话——Meta Llama 3的指令版本使用为对话系统设计的结构化提示格式。这种格式通过基于用户输入和预定义提示引导系统响应来保持连贯的交互。
  • 文本到SQL解析-对于文本到SQL分析等任务,请注意以下几点:
    • 有效的提示设计——工程师应该设计能够准确反映用户查询到SQL转换需求的提示。Meta Llama 3的功能提高了从自然语言输入中理解和生成SQL查询的准确性和效率。
  • 开发最佳实践——请记住以下几点:
    • 迭代细化——基于真实世界数据的提示结构的持续细化提高了不同应用程序的模型性能和一致性。
    • 验证和测试——彻底的测试和验证可确保快速工程模型在各种场景中可靠准确地运行,从而提高整体应用程序的有效性。
      通过实施这些实践,工程师可以优化Meta Llama 3模型在各种任务中的使用,从通用推理到专门的自然语言处理(NLP)应用程序,如文本到SQL解析,有效地利用模型的功能。

解决方案概述


使用LLM改进文本到SQL查询的需求越来越重要,因为它使非技术用户能够使用自然语言访问和查询数据库。这使生成式人工智能的访问民主化,并提高了编写复杂查询的效率,而无需学习SQL或理解复杂的数据库模式。例如,如果你是一名金融客户,并且你有一个跨越多个表的客户数据MySQL数据库,你可以使用Meta Llama 3模型从自然语言构建SQL查询。其他用例包括:

  • 提高准确性——得益于其先进的语言理解能力,LLM可以生成更准确地捕捉自然语言查询背后意图的SQL查询。这减少了重新表述或细化查询的需要。
  • 处理复杂性——LLM可以处理涉及多个表(我们在本文中演示了)、连接、过滤器和聚合的复杂查询,这对基于规则或传统的文本到SQL系统来说是具有挑战性的。这扩大了可以使用自然语言处理的查询范围。
  • 结合上下文——LLM可以使用数据库模式、表描述和关系等上下文信息来生成更准确和相关的SQL查询。这有助于弥合模糊的自然语言和精确的SQL语法之间的差距。
  • 可扩展性——经过培训后,LLM可以推广到新的数据库和模式,而无需进行大量的再培训或规则编写,使其比传统方法更具可扩展性。

对于该解决方案,我们遵循检索增强生成(RAG)模式,使用Amazon SageMaker JumpStart上的Meta Llama 3 70B模型从自然语言查询中生成SQL,该中心提供对预训练模型和解决方案的访问。SageMaker JumpStart提供了一种无缝、无忧的方式来部署和试验最新的最先进的LLM,如Meta Llama 3,而不需要复杂的基础设施设置或部署代码。只需点击几下,您就可以在虚拟私有云(VPC)控制下的安全AWS环境中启动并运行Meta Llama 3模型,从而维护数据安全。SageMaker JumpStart提供一系列Meta Llama 3型号尺寸(8B和70B参数)。这种灵活性允许您根据具体要求选择合适的型号尺寸。您还可以在部署之前逐步训练和调整这些模型。

该解决方案还包括托管在SageMaker JumpStart上的嵌入模型和公共可用的向量数据库,如ChromaDB,用于存储嵌入。

ChromaDB和其他矢量引擎


在文本到SQL应用程序领域,ChromaDB是一个功能强大、公开可用的嵌入式矢量数据库,旨在简化高维矢量数据的存储、检索和操作。ChromaDB与机器学习(ML)和NLP工作流程无缝集成,为语义搜索、推荐系统和基于相似性的分析等应用提供了一个强大的解决方案。ChromaDB提供了几个显著的功能:

  • 高效的矢量存储——ChromaDB使用先进的索引技术高效地存储和检索高维矢量数据,实现快速相似性搜索和最近邻查询。
  • 灵活的数据建模——您可以根据特定用例定义定制的集合和元数据模式,从而实现灵活的数据模型。
  • 无缝集成–ChromaDB可以无缝嵌入到现有的应用程序和工作流程中,为矢量数据管理提供轻量级和高性能的解决方案。


为什么选择ChromaDB用于文本到SQL用例?

  • 文本嵌入的高效向量存储——ChromaDB对高维向量嵌入的高效存储和检索对于文本到SQL任务至关重要。它支持文本嵌入的快速相似性搜索和最近邻查询,有助于将自然语言查询准确映射到SQL语句。
  • 与LLM无缝集成–ChromaDB可以快速与LLM集成,实现RAG架构。这允许LLM使用相关上下文,例如仅提供完成查询所需的相关表模式。
  • 可定制和社区支持——ChromaDB提供灵活性和定制性,拥有一个活跃的开发人员和用户社区,他们为ChromaDB的开发做出了贡献,提供了支持,并分享了最佳实践。这为文本到SQL应用程序提供了一个协作和支持的环境。
  • 经济高效–ChromaDB无需支付昂贵的许可费,使其成为各种规模组织的经济高效选择。


通过使用ChromaDB等矢量数据库引擎,您可以为特定用例获得更大的灵活性,并可以为生成式AI应用程序构建健壮且高性能的文本到SQL系统。

解决方案架构


该解决方案使用以下架构图中所示的AWS服务和功能。

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

工艺流程包括以下步骤:

  1. 用户发送一个文本查询,指定他们希望从数据库返回的数据。
  2. 数据库模式、表结构及其相关元数据通过SageMaker JumpStart上托管的嵌入模型进行处理,以生成嵌入。
  3. 这些嵌入以及有关表关系的其他上下文信息存储在ChromaDB中,以实现语义搜索,使系统在处理用户查询时能够快速检索相关的模式和表上下文。
  4. 查询被发送到ChromaDB,使用SageMaker JumpStart上托管的文本嵌入模型转换为向量嵌入。生成的嵌入用于在ChromaDB上执行语义搜索。
  5. 遵循RAG模式,ChromaDB输出与查询相关的表模式和表上下文。仅向Meta Llama 3 70B模型发送相关上下文。增强提示是使用ChromaDB中的此信息以及用户查询创建的。
  6. 增强提示被发送到SageMaker JumpStart上托管的Meta Llama3 70B模型,以生成SQL查询。
  7. 生成SQL查询后,您可以对MySQL的Amazon Relational Database Service(Amazon RDS)运行SQL查询,这是一种完全托管的云数据库服务,允许您快速操作和扩展MySQL等关系数据库。
  8. 从那里,输出被发送回SageMaker JumpStart上托管的Meta Llama 3 70B模型,为用户提供响应。
    响应已发送回用户。
  9. 根据您的数据所在的位置,您可以将此模式与其他关系数据库管理系统(如PostgreSQL)或其他数据库类型一起实现,具体取决于您现有的数据基础设施和特定要求。

 

先决条件


完成以下先决条件步骤:

拥有一个AWS帐户。
安装AWS命令行界面(AWS CLI)并设置Amazon SDK for Python(Boto3)。
在Amazon Bedrock控制台上请求模型访问权限,以访问Meta Llama 3模型。
可以使用Jupyter笔记本(无论是在本地还是在Amazon SageMaker Studio上)。
安装LangChain、Amazon Bedrock SDK(Boto3)和ChromaDB的包和依赖项。

将文本到SQL环境部署到您的AWS帐户

To deploy your resources, use the provided AWS CloudFormation template, which is a tool for deploying infrastructure as code. Supported AWS Regions are US East (N. Virginia) and US West (Oregon). Complete the following steps to launch the stack:

  1. On the AWS CloudFormation console, create a new stack.
  2. For Template source, choose Upload a template file then upload the yaml for deploying the Text-to-SQL environment.
  3. Choose Next.
  4. Name the stack text2sql.
  5. Keep the remaining settings as default and choose Submit.

The template stack should take 10 minutes to deploy. When it’s done, the stack status will show as CREATE_COMPLETE.

  1. When the stack is complete, navigate to the stack Outputs
  2. Choose the SagemakerNotebookURL link to open the SageMaker notebook in a separate tab.
  3. In the SageMaker notebook, navigate to the Meta-Llama-on-AWS/blob/text2sql-blog/RAG-recipes 
  4. directory and open llama3-chromadb-text2sql.ipynb.
  5. If the notebook prompts you to set the kernel, choose the conda_pytorch_p310 kernel, then choose Set kernel.

实施解决方案


您可以使用以下Jupyter记事本来构建解决方案,其中包括本节中提供的所有代码片段。在此解决方案中,您可以使用笔记本中的ask_for_service()选择将哪个服务(SageMaker Jumpstart或Amazon Bedrock)用作托管模型服务。Amazon Bedrock是一项完全管理的服务,提供高性能FM的选择。我们为您提供解决方案之间的选择,以便您的团队能够评估SageMaker JumpStart是否是首选,或者您的团队是否希望通过用户友好的Amazon Bedrock API减少运营开销。您可以选择使用SageMaker JumpStart来托管您选择的嵌入模型,也可以选择Amazon Bedrock来托管Amazon Titan嵌入模型(Amazon.Titan-embed-text-v2:0)。
现在笔记本已经准备好使用,请按照笔记本中的说明进行操作。通过这些步骤,您可以创建一个RDS for MySQL连接器,将数据集摄取到RDS数据库中,将表模式摄取到ChromaDB中,并生成文本到SQL查询来运行提示并分析驻留在Amazon RDS中的数据。

  • Create a SageMaker endpoint with the BGE Large En v1.5 Embedding model from Hugging Face:

    bedrock_ef = AmazonSageMakerEmbeddingFunction()
  • Create a collection in ChromaDB for the RAG framework:
chroma_client = chromadb.Client()
collection = chroma_client.create_collection(name="table-schemas-titan-embedding", embedding_function=bedrock_ef, metadata={"hnsw:space": "cosine"})
  • Bild the document with the table schema and sample questions to enhance the retriever’s accuracy:
doc1 = "<table_schemas>\n"
doc1 += f"<table_schema>\n {settings_airplanes['table_schema']} \n</table_schema>\n".strip()
doc1 += "\n</table_schemas>"
doc1 += f"\n<questions>\n {questions} \n</questions>"
  • Add documents to ChromaDB:
collection.add(
documents=[
doc1,
],
metadatas=[
{"source": "mysql", "database": db_name, "table_name": table_airplanes},
],
ids=[table_airplanes], # unique for each doc
)
  • Build the prompt (final_question) by combining the user input in natural language (user_query), the relevant metadata from the vector store (vector_search_match), and instructions (details):
instructions = [
{
"role": "system",
"content":
"""You are a mysql query expert whose output is a valid sql query.
Only use the following tables:
It has the following schemas:
<table_schemas>
{table_schemas}
<table_schemas>
Always combine the database name and table name to build your queries. 
You must identify these two values before proving a valid SQL query.
Please construct a valid SQL statement to answer the following the question, return only the 
mysql query in between <sql></sql>.
"""
},
{
"role": "user",
"content": "{question}"
}
]
tmp_sql_sys_prompt = format_instructions(instructions)
Submit a question to ChromaDB and retrieve the table schema SQL
# Query/search 1 most similar results.
docs = collection1.query(
query_texts=[question],
n_results=1
)
pattern = r"<table_schemas>(.*)</table_schemas>"
table_schemas = re.search(pattern, docs["documents"][0][0], re.DOTALL).group(1)
print(f"ChromaDB - Schema Retrieval: \n{table_schemas.strip()}")
  • Invoke Meta Llama 3 on SageMaker and prompt it to generate the SQL query. The function get_llm_sql_analysis will run and pass the SQL query results to Meta Llama 3 to provide a comprehensive analysis of the data:
# Generate a prompt to get the LLM to provide an SQL query
SQL_SYS_PROMPT = PromptTemplate.from_template(tmp_sql_sys_prompt).format(
question=question,
table_schemas=table_schemas,
)
results = get_llm_sql_analysis(
question=question,
sql_sys_prompt=SQL_SYS_PROMPT,
qna_sys_prompt=QNA_SYS_PROMPT
)

Although Meta Llama 3 doesn’t natively support function calling, you can simulate an agentic workflow. In this approach, a query is first generated, then run, and the results are sent back to Meta Llama 3 for interpretation.

Run queries

For our first query, we provide the input “How many unique airplane producers are represented in the database?” The following is the table schema retrieved from ChromaDB:

<table_schema>
CREATE TABLE airline_db.airplanes -- Table name
(
Airplane_id INT(10), -- airplane id
Producer VARCHAR(20), -- name of the producer
Type VARCHAR(10), -- airplane type
PRIMARY KEY (Airplane_id)
)
</table_schema>

The following is the generated query:

SELECT COUNT(DISTINCT Producer) FROM airline_db.airplanes;

The following is the data analysis generated from the previous SQL query:

Based on the SQL query results, we can see that the output is a single value: `(4)`.
This result indicates that there are **4 unique airplane producers** represented in the database.
In other words, the query has counted the number of distinct airplane producers in the database, and the 
answer is 4. This means that there are four different companies or entities that produce airplanes, 
and they are all represented in the database.
Therefore, the answer to the original question is: **There are 4 unique airplane producers represented 
in the database.**

For our second query, we ask “Find the airplane IDs and producers for airplanes that have flown to New York.” The following are the table schemas retrieved from ChromaDB:


<table_schema>
CREATE TABLE airline_db.airplanes -- Table name
(
Airplane_id INT(10), -- airplane id
Producer VARCHAR(20), -- name of the producer
Type VARCHAR(10), -- airplane type
PRIMARY KEY (Airplane_id)
)

</table_schema>
<table_schema>
CREATE TABLE airline_db.flights -- Table name
(
Flight_number VARCHAR(10), -- flight id
Arrival_time VARCHAR(20), -- arrival time (YYYY-MM-DDTH:M:S)
Arrival_date VARCHAR(20), -- arrival date (YYYY-MM-DD)
Departure_time VARCHAR(20), -- departure time (YYYY-MM-DDTH:M:S)
Departure_date VARCHAR(20), -- departure date (YYYY-MM-DD)
Destination VARCHAR(20), -- destination
Airplane_id INT(10), -- airplane id
PRIMARY KEY (Flight_number),
FOREIGN KEY (Airplane_id) REFERENCES airplanes(Airplane_id)
)

</table_schema>

The following is our generated query:

SELECT a.Airplane_id, a.Producer
FROM airline_db.airplanes a
JOIN airline_db.flights f ON a.Airplane_id = f.Airplane_id
WHERE f.Destination = 'New York';

The following is the data analysis generated from the previous SQL query:

Based on the provided SQL query results, we can analyze and interpret the output as follows:
The result set contains a single row with two columns:
* `airplane_id`: 6
* `producer`: 'Airbus'
This suggests that there is only one airplane that has flown to New York, and its 
details are as follows:
* The airplane has an ID of 6.
* The producer of this airplane is Airbus.
Therefore, the answer to the original question is that the airplane with ID 6, 
produced by Airbus, 
has flown to New York.

 

 

 

清理


为了避免产生持续的AWS使用费用,请删除您在本文中创建的所有资源。在删除CloudFormation堆栈之前,请确保删除在应用程序中创建的SageMaker端点。

结论


在这篇文章中,我们探索了一种解决方案,该解决方案使用矢量引擎ChromaDB和Meta Llama 3,Meta Llima 3是SageMaker JumpStart上托管的公开FM,用于文本到SQL用例。我们分享了Meta Llama 3的简要历史、Meta Llama 3模型的快速工程最佳实践,以及使用少量镜头提示和RAG提取存储在ChromaDB中的相关模式的架构模式。最后,我们提供了一个包含代码示例的解决方案,让您可以灵活地选择SageMaker Jumpstart或Amazon Bedrock,以获得更受管理的体验,从而托管Meta Llama 3 70B、Meta Llama3 8B和嵌入模型。

使用公共可用的功能模块和服务以及AWS服务有助于提高灵活性,并对所使用的工具提供更多控制。我们建议遵循SageMaker JumpStart GitHub仓库获取入门指南和示例。解决方案代码也可在以下Github仓库中获得。

我们期待您的反馈和想法,了解如何将这些计算应用于您的业务需求。

本文地址
最后修改
星期六, 十一月 15, 2025 - 11:23
Article