Published · 10 min read

构建通用AI代理

大型語言模型自定義開發入門指南:解決簡單用例

作者: 瑞秋·馬丁內斯 | 角色: 開發人員 | 標籤: AI 代理


介紹

歡迎來到我們的技術博客,我們在這裡使複雜的概念變得人人可懂,無論你的背景如何。今天,我們要深入探討一個令人興奮的項目:開發一種可以適應各種任務的大型語言模型(LLM)代理

我們將創建一個強大的檢索、增強和生成(RAG)基礎設施,以幫助我們為每個任務選擇最合適的 LLM。像 H2O 和 HuggingFace 這樣的公司已經推出了類似的系統,我們也收到了初創公司的興趣,他們渴望將我們的 AI 技術整合到他們的應用程序中

我們的特定用例需要使用單一輸入(一次性)或鏈接多個提示來提示 LLM。這需要為各種場景創建可自定義和用戶友好的 LLM 模組

請繼續關注我們的旅程,我們將以簡單和吸引人的方式分解每一步

目前用例

在我們目前的用例中,我們通過兩步驟增強用戶簡歷的內容:

  1. 輸入: 用戶將簡歷的「專業摘要」和「經驗」部分輸入到系統中,然後查詢 LLM 生成文本的更精煉版本
  2. 审阅: 用户审阅LLM生成的内容,并提供额外的提示或指导以完善和个性化输出,确保其符合他们独特的技能和经验。

通过这种方法,用户可以利用LLM的力量,打造出令人信服的简历,吸引潜在雇主的注意。

目标

我们旨在构建一个完全可定制的LLM模块,以支持我们的用例,并至少部分自动化简历创建过程。

实施

步骤1:选择LLM

在选择适合您需求的LLM时,有两个主要类别需要考虑:开源LLM和专有LLM。我们将讨论这两个群体中流行的选项,重点介绍选择开源LLM的益处。

开源LLM

示例: Mistral AI,Phi 3,LLaMa 3。

优势:

  • 社区支持: 大型、活跃的开发者和用户社区提供指导、共享资源和合作改进。
  • 可定制性: 可访问源代码,允许修改和适应特定用例。
  • 透明度: 了解模型的内部工作原理对于具有严格的道德或隐私指南的应用程序至关重要。

专有LLM

示例: GPT-4。

优点:令人印象深刻的性能和独特的功能。

限制:

  • 缺乏可定制性: 仅限使用模型的现状。
  • 成本: 基于使用的费用会随着时间的推移而增加。
  • 不透明的性质: 难以理解底层的机制,这可能是优先考虑透明度和可解释性的问题。

总之,虽然开源和专有LLM都有其优点和缺点,但像Mistral AI、Phi 3和LLaMa 3这样的开源LLM提供了可访问性、可定制性和透明度,这对于广泛的用户来说是非常有益的。

步骤2:查看成本和功能

开源LLM通常是成本有效的,因为它们可以托管在自己的服务器上或与提供商如Azure或AWS一起使用,采用按需付费模式。以下是托管各种LLM的成本和功能的总结:

LLM详细信息上下文长度费用
Mixtral 8x7BMoE LLM 由Mistral A训练:8192 个令牌$0.7/1M 令牌(廉价)
Mixtral 8x22BMixtral 的继任者训练:32768 个令牌$2/1M 令牌(可用)
LLaMa 3 70B非MoE模型,由 Met 开发训练:2048 个令牌$0.02/1K 令牌(Azu)
Phi 3 128K多模态-SLM 由 Me 开发训练和总计:3$0.002/1K 令牌(Az)
GPT-4 Turbo专有 LLM 由 O 开发默认 16K,较高在 AWS 上不可用

步骤 3:使用符合 OpenRouter 的公共 API 进行测试

选择和测试最佳的 LLM 需要一种简化的方式来访问和评估不同的模型。 OpenRouter,一个开源的 API 标准,实现了在各种 AI 模型和服务之间的无缝切换。我们选择了 Fireworks AI 作为我们的提供者,因为:

  • 模型多样性:提供了广泛的 AI 模型,包括流行的开源 LLMs,如 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",""))
模型延迟备注
Mixtral 8x7B2.1s最轻量级模型,性能
混合模型 8x22B5.3秒继任模型,模拟
LLaMa 3 70B2.6秒还不错的响应,但
Phi 3 128K1.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
                            。在我最后一年管理一个专注于区块链解决方案的团队时

{'experience': [{'title': '软件工程师',
                'company': 'TechCorp',
                'location': '悉尼',
                'start_date': '2011-01',
                'end_date': '2018-12',
                'highlights': ['- 设计了大型项目的可扩展数据库系统,提高了客户数据处理速度40%。',
                              '- 领导了一个专注于AI驱动解决方案的团队。',
                              '- 开发了AI驱动的金融分析工具,处理100M+记录的分布式环境。',
                              '- 创建了公司的专有数据管道。'
                              '- 管理团队开发区块链解决方案,任职至最后一年。']}]}

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:

  1. User Input: The journey begins when the user enters their details, such as the “about” and “experience” sections of their resume, into the system.
  2. 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.
  3. 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.
  4. 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.
  5. 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.
  6. 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.
  7. 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-字符串一样工作。这里的 chat_model 是我们正在使用的 LLM,并且被链接到提示中。|(管道)运算符类似于 BASH 的 | 运算符,表示一个链。这是由 LCEL (LangChain 表达式语言)规范提供的方便的简写。它允许将一个提示的响应链接到另一个提示的输入。它还支持函数调用,也就是说,可以链接 lambda 表达式或某些函数来清理输出。这通过简单地编写链而不是大型函数来减少代码的复杂性。

步骤 5:使用 VectorDBs

向量数据库(VectorDBs)存储、管理和高效搜索高维向量,例如由 LLMs 生成的文本嵌入。以下是流行选项的比较:

Qdrant

优点:高性能,易于集成,活跃的社区。

缺点:无显著缺点。

Milvus

优点:多种距离度量,数据可视化工具。

缺点:学习曲线较陡。

色彩

优点: 易于使用的Python API,模块化设计。

缺点: 相对较新,社区支持较少。

PGVector

优点: 利用PostgreSQL的能力,基于SQL的查询。

缺点: 对高维向量搜索性能较差。

FAISS

优点: 高性能搜索,支持GPU。

缺点: 需要与其他数据库集成。

Qdrant的可扩展性、易于集成和活跃的开发使其成为我们AI驱动解决方案的合适选择。

利用VectorDBs作为强大的IR解决方案

使用VectorDBs创建信息检索(IR)解决方案涉及:

  1. 文本预处理: 清理和预处理原始文本数据。
  2. 文本嵌入生成: 使用LLM将预处理的文本转换为高维向量。
  3. 在VectorDB中存储嵌入: 为高效搜索而索引嵌入。
  4. 查询处理: 预处理和将用户查询转换为嵌入。
  5. 相似性搜索: 在VectorDB中执行相似性搜索以找到相关嵌入。
  6. 排名和显示结果: 对检索的嵌入进行排名并将其转换回文本以显示。

通过遵循此过程并利用VectorDBs,可以构建一个高效且有效的IR系统。

准备好精准招聘了吗?

免费开始,邀请整个团队,15 分钟内看到第一位已评分的候选人。

zh