《开发可定制的大语言模型以解决简单用例的初学者指南》
作者: Rachel Martinez | 角色: 开发者 | 标签: AI Agents
介绍
欢迎来到我们的技术博客,在这里我们将复杂的概念变得通俗易懂,无论您的背景如何。今天,我们启动了一个激动人心的项目:开发一个大型语言模型(LLM)智能体,使其能够适应各种任务。
我们将构建一个强大的检索、增强和生成(RAG)基础设施,以协助我们选择最适合每个任务的 LLM。H2O和HuggingFace等公司已经推出了类似系统,我们收到了来自初创企业的兴趣反馈,他们渴望将我们的AI技术集成到其应用中。
我们的特定用例要求能够通过单一输入(一次提示)或组合多个提示来对 LLM 进行提示。这需要为各种场景创建可定制且用户友好的 LLM 模块。
敬请期待,我们将踏上这段旅程,以简单且引人入胜的方式逐步解析每一个环节。
当前用例
在我们的当前用例中,我们通过一个两步流程来增强用户简历的内容:
- 用户将简历中的“专业总结”和“工作经历”部分输入系统,并查询 LLM 以生成更精炼的版本。
- 审核:用户审核由 LLM 生成的内容,并提供额外的提示或指导以优化和个性化输出,确保其符合用户的独特技能和经验。
通过采用这种方法,用户能够利用 LLM 的强大功能,打造一份引人注目的简历,从而在众多求职者中脱颖而出,吸引潜在雇主的关注。
目标
我们旨在打造一个完全可定制的 LLM 模块,以支持我们的业务场景,并至少部分实现简历创建流程的自动化。
实施
第一步:选择 LLM
选择合适的LLM时,主要有两大类别需要考虑:开源LLMs和专有LLMs。我们将讨论这两个群体中的热门选项,重点介绍选择开源LLMs的益处。
开源大语言模型
Mistral AI,Phi 3,LLaMa 3
优点:
- 社区支持:庞大且活跃的开发者与用户社区提供指导、分享资源,并协作改进。
- 可定制性:访问源代码允许进行修改和适配,以满足特定用例的需求。
- 透明度:了解模型的内部工作机制对于严格遵守伦理或隐私准则的应用至关重要。
专有大型语言模型
GPT-4
优点:性能出色,功能独特。
限制
- 缺乏可定制性:仅限于直接使用模型,无法进行自定义调整。
- 成本:按用量计费的费用可能会随时间累积。
- 不透明性:难以理解其底层机制,这对于重视透明度和可解释性的用户来说可能是一个问题。
总之,尽管开源和专有大型语言模型各有优劣,但像 Mistral AI、Phi 3 和 LLaMa 3 这样的开源 LLM 具备可访问性、可定制性和透明度等优势,能够为各类用户带来显著益处。
第二步:查看成本与功能
开源大语言模型通常具有较高的成本效益,因为它们可以托管在您自己的服务器上,或者通过按使用量付费的模式在 Azure 或 AWS 等平台上运行。以下是托管各种大型语言模型的成本与功能概览:
| LLM | 详情 | 上下文长度 | 成本 |
|---|---|---|---|
| 混合专家模型 8x7B | MoE LLM 由 Mistral A | 已训练:8192 个令牌 | $0.7/1M代币(chea |
| 混合模型 8x22B | Mixtral的继任者 | 已训练:32768 个 token | 每100万令牌2美元(可用 |
| LLaMa 3 70B | 非MoE模型,由Met开发 | 已训练:2048 个标记 | $0.02/1K tokens (Azu |
| Phi 3 128K | 多模态-SLM,由Me开发 | 训练和总计:3 | $0.002/1K代币(Az |
| GPT-4 涡轮 | O公司专有的LLM | 16K 默认,更高 | AWS 上不可用 |
步骤3:使用符合OpenRouter的公共API进行测试
选择和测试最佳的LLM需要一种简化的方式来访问和评估不同的模型。OpenRouter,一个开源的API标准,实现了无缝切换各种AI模型和服务。我们选择了Fireworks AI作为我们的提供商,因为:
- 模型多样性:提供多种 AI 模型,包括流行的开源大语言模型,如 Mistral AI、Phi 3 和 LLaMa 3。
- 集成简便:符合OpenRouter标准,简化了现有基础设施的集成。
- 可扩展性:设计用于处理大量请求,并能够无缝扩展。
以下是使用相同硬件调用模型响应及延迟结果的示例函数:
import json
def get_sanitized_json_response(user_input, guardrail):
final = chain.invoke({"text": f"Sanitize {user_input}. Guardrail: {guardrail}"})
final = chain.invoke({"text": final.content})
return json.loads(final.content.replace("<json>", "").replace("</json>", "").replace("\n",""))
| 模型 | 延迟 | 备注 |
|---|---|---|
| 混合模型 8x7B | 2.1秒 | 最轻型号,性能 |
| 混合专家模型 8x22B | 5.3秒 | 后继型号,模拟 |
| LLaMa 3 70B | 2.6秒 | 不错的回应,但 |
| Phi 3 128K | 1.5 分钟 | 多模态模型 |
使用了非常简单的护栏和输入来测试上述内容:
guardrail = """Format details as bullets and use the XYZ method to format the relevant detail.
For example:
- I did X boosting Y percent resulting in Z.
"""
调用后,我们得到了以下经过清理的 JSON 响应:
get_sanitized_json_response("""I served as Junior as a Software Engineer at TechCorp in Sydney in January 2011 and worked there until December 2018. During my tenure,
我领导团队开发了先进的基于AI的金融分析工具,用于处理数以亿计的记录
分布式环境,并创建了公司专有数据管道的初始版本。在我的角色中,我负责
设计解决方案并实施多个 API。在我管理专注于区块链解决方案的团队的那一年。”
{'经验': [{'职位': '软件工程师',
'公司': 'TechCorp',
'位置': '悉尼',
“开始日期”:'2011-01',
'结束日期': '2018-12',
“亮点:- 设计并实现了可扩展的数据库系统,使客户数据处理速度提升了40%。”
‘领导团队,专注于基于AI的解决方案。’
“开发基于AI的财务分析工具,在分布式环境中处理超过1亿条记录。”
'- 创建了公司的专有数据管道。'
“- 在最后一年的区块链解决方案中管理团队。”
In conclusion, since the response quality was fairly comparable among all these models, it came down to latency and cost. The experiment was run 3 times achieving very similar results. So we chose Mistral AI’s Mixtral 8x7B due to its favorable balance of latency and cost.
Step 4: Building an Orchestration Layer
Managing and coordinating multiple large-scale language models or a single model across various applications is crucial for optimal performance and adaptability. Instead of building from scratch using vanilla PyTorch, employing an orchestration framework is more practical and efficient. Here are three options:
Langchain
Advantages: Vast array of integrations, supports Python and JavaScript, extensive community support.
Drawbacks: Introduces an additional dependency, potential learning curve.
LlamaIndex
Advantages: Backed by Meta, offers interoperability with Langchain.
Drawbacks: Less developer-friendly syntax.
Haystack
Advantages: User-friendly syntax, supported by prominent tech corporations.
Drawbacks: Limited integrations as it’s still maturing.
Using an orchestration framework simplifies development, improves scalability, and provides access to a supportive community, making it a more favorable choice for our project.
Design and Data Flow
The following image shows the design diagram:
The data flow within our AI-driven system is an essential aspect of ensuring a seamless and efficient user experience. While the design diagram provides a visual representation of the process, a detailed explanation can help clarify the steps involved:
- User Input: The journey begins when the user enters their details, such as the “about” and “experience” sections of their resume, into the system.
- Prompt Generation: The user’s input is then processed and transformed into one or more prompts, which will be used to query the Large Language Model (LLM) for a more polished and impressive version of the text.
- LLM Integration via Langchain: The generated prompts are passed to Langchain, our chosen orchestrator framework, which facilitates the interaction with the LLM client. Langchain leverages a Pydantic schema in the form of a class to parse and validate the data using kor, ensuring that it adheres to the required format.
- JSONResponse Generation: Once the data is validated, it is converted into a final JSONResponse, a structured and easy-to-work-with data format that simplifies further processing and manipulation.
- Content Extraction and Indexing: The content part of the JSONResponse is extracted using kor and indexed by computing embeddings, which are mathematical representations of the text. These embeddings are then stored in a vector database, such as Qdrant, for efficient retrieval and comparison during subsequent queries.
- Caching for Context Module: The entire JSONResponse is cached for the context module to function correctly. This ensures that the system can maintain the context of the user’s input and the LLM’s output during follow-up queries.
- Follow-up Queries: When the user provides additional input or requests further refinement of the generated text, the cached JSONResponse is modified according to the new context and chained to the updated prompt. This modified prompt then goes through the entire process again, from LLM integration to content extraction and indexing, to provide the user with a tailored and accurate response.
By understanding the data flow within our system, we can appreciate the importance of each step and the role of the orchestrator framework in streamlining the process, ultimately resulting in an efficient and user-friendly AI-driven solution.
使用 LCEL 进行提示构建与链接
这是 PromptTemplate 的示例:
from langchain.core.output_parsers import PydanticOutputParser
prompt = PromptTemplate(
template="Please extract the following information from the given text and format it as a JSON object according to the schema:\n\n{format_instructions}\n{query}\n",
input_variables=["query"],
partial_variables={"format_instructions": output_parser.get_format_instructions()},
)
chain = prompt | chat_model | output_parser
一个典型的模板包含两个主要参数(还有更多,但这超出了本博客的范围),即 input_variables 和 template。第一个参数接受一个字符串列表,这些字符串将在运行时被注入到提示模板中。该变量通常表现得类似于 Jinja2Template 或 f-strings。这里的 chat_model 是我们正在使用的 LLM,并且它被链接到了提示词中。“|”(管道)运算符类似于 BASH 的 “|” 运算符,表示链式调用。这是 LCEL(LangChain 表达式语言)规范给出的一个便捷的简写。这将使我们能够将一个提示的响应链接到另一个提示的输入。它还支持函数调用,也就是说,可以将 lambda 表达式或某些函数链接起来,通常用于对输出进行清理。通过编写链式调用而非大型函数,降低了代码的复杂度。
步骤5:使用VectorDBs
向量数据库(VectorDBs)存储、管理并高效搜索高维向量,例如由大型语言模型生成的文本嵌入。以下是热门选项的对比:
Qdrant
优点:高性能,易于集成,拥有活跃的社区。
缺点:无明显缺点。
米卢斯
优点:多种距离度量方法,数据可视化工具。
缺点:学习曲线较陡峭。
色度
优点:Python、API易于使用,模块化设计。
缺点:相对较新,社区支持不够广泛。
PGVector
优势:利用 PostgreSQL 的能力,基于 SQL 的查询。
缺点:在高维向量搜索中性能较低。
FAISS
优势:高性能搜索,支持 GPU。
缺点:需要与其他数据库集成。
Qdrant的可扩展性、易于集成以及活跃的 developments 使其成为我们基于AI的解决方案的理想选择。
将 VectorDBs 作为稳健的 IR 解决方案
使用 VectorDBs 创建信息检索(IR)解决方案涉及:
- 文本预处理:对原始文本数据进行清洗和预处理。
- 文本嵌入生成:使用 LLM 将预处理后的文本转换为高维向量。
- 在 VectorDB 中存储嵌入:索引嵌入以实现高效搜索。
- 查询处理:预处理并将用户查询转换为嵌入向量。
- 相似度搜索:在 VectorDB 中执行相似度搜索以查找相关嵌入。
- 排序与展示结果:对检索到的嵌入向量进行排序,并将其转换回文本以供展示。
通过遵循这一流程并利用 VectorDBs,我们可以构建一个高效且有效的 IR 系统。