跳到主要内容

使用 LangChain 和 MLflow 入门

下载此笔记本

欢迎来到本交互式教程,旨在向您介绍 LangChain 及其与 MLflow 的集成。本教程结构为一个笔记本,提供对 LangChain 最简单、最核心功能的实践、动手学习体验。

您将学到什么

  • 了解 LangChain:了解 LangChain 的基础知识及其在开发由语言模型驱动的应用程序中的应用。
  • LangChain 中的 Chains:探索 LangChain 中 chains 的概念,它们是为执行复杂任务而编排的一系列操作或指令。
  • 与 MLflow 集成:学习 LangChain 如何与 MLflow 集成,MLflow 是一个用于管理机器学习生命周期的平台,包括模型日志记录、跟踪和部署。
  • 实际应用:运用您的知识构建一个充当副厨师的 LangChain chain,专注于食谱的准备步骤。

LangChain 背景

LangChain 是一个基于 Python 的框架,它简化了使用语言模型的应用程序的开发。它旨在增强应用程序的上下文感知能力和推理能力,从而实现更复杂和交互式的功能。

什么是 Chain?

  • Chain 定义:在 LangChain 中,chain 指的是为完成特定任务而设计的一系列相互连接的组件或步骤。
  • Chain 示例:在本教程中,我们将创建一个模拟副厨师在准备食谱中的食材和工具的 chain。

教程概述

在本教程中,您将

  1. 设置 LangChain 和 MLflow:初始化并配置 LangChain 和 MLflow。
  2. 创建副厨师 Chain:开发一个 LangChain chain,用于列出食材、描述准备技术、组织食材的准备以及为给定食谱准备烹饪用具。
  3. 日志记录和加载模型:利用 MLflow 来记录 chain 模型,然后加载它以进行预测。
  4. 运行预测:执行 chain,了解它如何为特定数量的顾客准备一道餐厅菜肴。

在本教程结束时,您将对使用 LangChain 和 MLflow 有扎实的基础,并理解如何构建和管理 chain 以用于实际应用。

让我们一起深入探索 LangChain 和 MLflow 的世界吧!

先决条件

为了开始本教程,我们首先需要一些东西。

  1. OpenAI API 账户。您可以在此处注册以获得访问权限,从而开始以编程方式访问地球上领先的高级 LLM 服务之一。
  2. OpenAI API 密钥。创建账户后,可以通过导航到API 密钥页面来访问此密钥。
  3. OpenAI SDK。它在此处 PyPI 上提供。在本教程中,我们将使用版本 0.28.1(1.0 版本之前的最后一个发布版本)。
  4. LangChain 包。您可以在此处 PyPI 上找到它

Notebook 兼容性

随着 langchain 等库的快速发展,示例可能会很快过时且不再有效。出于演示目的,以下是建议使用的关键依赖项,以有效运行此笔记本

软件包版本
langchain0.1.16
lanchain-community0.0.33
langchain-openai0.0.8
openai1.12.0
tiktoken0.6.0
mlflow2.12.1

如果您尝试使用不同的版本执行此 Notebook,它可能可以正常运行,但建议使用上述精确版本,以确保您的代码正确执行。

要安装依赖包,只需运行

bash
pip install openai==1.12.0 tiktoken==0.6.0 langchain==0.1.16 langchain-openai==0.0.33 langchain-community==0.0.33 mlflow==2.12.1

注意:本教程不支持 openai<1,并且不保证与 langchain<1.16.0 的版本兼容

API 密钥安全概述

API 密钥,尤其是对于 SaaS 大型语言模型 (LLM),由于与账单相关,因此与财务信息一样敏感。

如果您有兴趣了解有关安全管理访问密钥的替代 MLflow 解决方案的更多信息,请在此处阅读 MLflow AI Gateway

基本实践:

  • 保密性:始终保持 API 密钥的私密性。
  • 安全存储:优先使用环境变量或安全服务。
  • 定期轮换:定期更新密钥以避免未经授权的访问。

配置 API 密钥

为了安全使用,请将 API 密钥设置为环境变量。

macOS/Linux:有关在终端中使用环境变量的详细说明,请参阅Apple 的指南

Windows:请遵循Microsoft 关于环境变量的文档中概述的步骤。

python
import os

from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate
from langchain_openai import OpenAI

import mlflow

assert "OPENAI_API_KEY" in os.environ, "Please set the OPENAI_API_KEY environment variable."

注意:如果您想使用 Azure OpenAI 与 LangChain,您需要安装 openai>=1.10.0langchain-openai>=0.0.6,并指定以下凭据和参数

python
# NOTE: Only run this cell if you are using Azure interfaces with OpenAI. If you have a direct account with
# OpenAI, ignore this cell.

from langchain_openai import AzureOpenAI, AzureOpenAIEmbeddings

# Set this to `azure`
os.environ["OPENAI_API_TYPE"] = "azure"
# The API version you want to use: set this to `2023-05-15` for the released version.
os.environ["OPENAI_API_VERSION"] = "2023-05-15"
assert "AZURE_OPENAI_ENDPOINT" in os.environ, (
"Please set the AZURE_OPENAI_ENDPOINT environment variable. It is the base URL for your Azure OpenAI resource. You can find this in the Azure portal under your Azure OpenAI resource."
)
assert "OPENAI_API_KEY" in os.environ, (
"Please set the OPENAI_API_KEY environment variable. It is the API key for your Azure OpenAI resource. You can find this in the Azure portal under your Azure OpenAI resource."
)

azure_openai_llm = AzureOpenAI(
deployment_name="<your-deployment-name>",
model_name="gpt-4o-mini",
)
azure_openai_embeddings = AzureOpenAIEmbeddings(
azure_deployment="<your-deployment-name>",
)

在 LangChain 中配置 OpenAI Completions 模型

在本教程的这一部分,我们已使用适合生成语言补全的特定参数配置了 OpenAI 模型。我们使用的是 Completions 模型,而不是 ChatCompletions 模型,这意味着每个请求都是独立的,并且每次都需要包含整个提示才能生成响应。

理解 Completions 模型

  • Completions 模型:此模型不维护请求之间的上下文信息。它非常适合每个请求都是独立且不依赖于过去交互的任务。为各种非对话式应用程序提供灵活性。

  • 无上下文记忆:缺乏对先前交互的记忆意味着该模型最适合一次性请求或不需要对话连续性的场景。

  • 与 ChatCompletions 模型类型的比较:专为会话式 AI 而设计,可在多次交互中维护上下文以进行连续对话。适用于聊天机器人或对话历史至关重要的应用程序。

在本教程中,我们使用 Completions 模型是因为它简单有效,可以处理单个、独立的请求,这与本教程侧重于烹饪前的准备步骤的重点相符。

python
llm = OpenAI(temperature=0.1, max_tokens=1000)

副厨师模拟模板指令说明

在本教程的这一部分,我们创建了一个详细的提示模板,用于模拟高级餐厅副厨师的角色。此模板旨在指导 LangChain 模型进行菜肴准备,仅专注于mise-en-place 过程。

模板指令细分

  • 副厨师角色扮演:提示将语言模型置于副厨师的角色,强调细致的准备工作。

  • 任务大纲:

    1. 列出配料:指示模型列出给定菜肴所需的所有配料。
    2. 准备技术:要求模型描述配料准备所需的技术,例如切割和处理。
    3. 配料准备:要求模型提供每种配料的详细准备说明,考虑使用顺序和时间。
    4. 烹饪用具准备:指导模型列出并准备菜肴准备阶段所需的所有烹饪工具。
  • 范围限制:模板明确设计为在准备阶段停止,避免实际烹饪过程。它专注于设置厨师开始烹饪所需的一切。

  • 动态输入:该模板可适应不同的食谱和顾客数量,如占位符 {recipe}{customer_count} 所示。

此模板指令是本教程的关键组成部分,演示了如何利用 LangChain 声明具有参数化功能的指令性提示,这些提示面向单用途的 completions 风格应用程序。

python
template_instruction = (
"Imagine you are a fine dining sous chef. Your task is to meticulously prepare for a dish, focusing on the mise-en-place process."
"Given a recipe, your responsibilities are: "
"1. List the Ingredients: Carefully itemize all ingredients required for the dish, ensuring every element is accounted for. "
"2. Preparation Techniques: Describe the techniques and operations needed for preparing each ingredient. This includes cutting, "
"processing, or any other form of preparation. Focus on the art of mise-en-place, ensuring everything is perfectly set up before cooking begins."
"3. Ingredient Staging: Provide detailed instructions on how to stage and arrange each ingredient. Explain where each item should be placed for "
"efficient access during the cooking process. Consider the timing and sequence of use for each ingredient. "
"4. Cooking Implements Preparation: Enumerate all the cooking tools and implements needed for each phase of the dish's preparation. "
"Detail any specific preparation these tools might need before the actual cooking starts and describe what pots, pans, dishes, and "
"other tools will be needed for the final preparation."
"Remember, your guidance stops at the preparation stage. Do not delve into the actual cooking process of the dish. "
"Your goal is to set the stage flawlessly for the chef to execute the cooking seamlessly."
"The recipe you are given is for: {recipe} for {customer_count} people. "
)

构建 LangChain Chain

我们首先在 LangChain 中设置一个 PromptTemplate,它针对我们的副厨师场景进行了定制。该模板旨在动态接受诸如食谱名称和顾客数量之类的输入。然后,我们将我们的 OpenAI 语言模型与提示模板结合起来,初始化一个 LLMChain,创建一个可以模拟副厨师准备过程的 chain。

在 MLflow 中记录 Chain

准备好 chain 后,我们继续在 MLflow 中记录它。这将在 MLflow 运行中完成,它不仅会记录指定名称下的 chain 模型,还会跟踪有关模型的各种详细信息。日志记录过程确保 chain 的所有方面都被记录下来,从而实现高效的版本控制和未来的检索。

python
prompt = PromptTemplate(
input_variables=["recipe", "customer_count"],
template=template_instruction,
)
chain = LLMChain(llm=llm, prompt=prompt)

mlflow.set_experiment("Cooking Assistant")

with mlflow.start_run():
model_info = mlflow.langchain.log_model(chain, name="langchain_model")

如果我们导航到 MLflow UI,我们将看到我们记录的 LangChain 模型。

Our LangChain Model in the MLflow UI

使用 MLflow 加载模型和进行预测

在本教程的这一部分,我们将演示使用 MLflow 对记录的 LangChain 模型进行实际应用。我们加载模型并针对特定菜肴运行预测,展示了模型在烹饪准备方面的协助能力。

模型加载和执行

在 MLflow 中记录我们的 LangChain chain 后,我们将使用 MLflow 的 pyfunc.load_model 函数继续加载模型。这一步至关重要,因为它将我们之前记录的模型带入可执行状态。

然后,我们将特定的食谱和顾客数量输入到我们的模型中。在此示例中,我们使用了“红酒炖牛肉”的食谱,并指定它是为 12 位顾客准备的。模型充当副厨师,处理这些信息并生成详细的准备说明。

模型输出

模型的输出提供了关于准备“红酒炖牛肉”的全面指南,涵盖了几个关键方面

  • 配料列表:详细列出所有必需的配料,量化并根据指定的顾客数量进行调整。
  • 准备技术:遵循 mise-en-place 原则,对每种配料的准备方法进行分步说明。
  • 配料准备:关于如何组织和准备配料的指南,确保在烹饪过程中能够高效地取用和使用。
  • 烹饪用具准备:关于准备必要的烹饪工具和用具的说明,从锅、平底锅到碗和滤锅。

这个例子展示了将 LangChain 和 MLflow 结合用于实际场景的力量和实用性。它强调了这种集成如何有效地将复杂的需求转化为可行的步骤,从而协助需要精确性和仔细计划的任务。

python
loaded_model = mlflow.pyfunc.load_model(model_info.model_uri)

dish1 = loaded_model.predict({"recipe": "boeuf bourginon", "customer_count": "4"})

print(dish1[0])
1. Ingredients:
- 2 pounds beef chuck, cut into 1-inch cubes
- 6 slices of bacon, diced
- 2 tablespoons olive oil
- 1 onion, diced
- 2 carrots, diced
- 2 cloves of garlic, minced
- 1 tablespoon tomato paste
- 1 bottle of red wine
- 2 cups beef broth
- 1 bouquet garni (thyme, bay leaf, parsley)
- 1 pound pearl onions, peeled
- 1 pound mushrooms, quartered
- Salt and pepper to taste
- Chopped parsley for garnish

2. Preparation Techniques:
- Cut the beef chuck into 1-inch cubes and set aside.
- Dice the bacon and set aside.
- Peel and dice the onion and carrots.
- Mince the garlic cloves.
- Prepare the bouquet garni by tying together a few sprigs of thyme, a bay leaf, and a few sprigs of parsley with kitchen twine.
- Peel the pearl onions and quarter the mushrooms.

3. Ingredient Staging:
- Place the beef cubes in a bowl and season with salt and pepper.
- In a large Dutch oven, heat the olive oil over medium-high heat.
- Add the diced bacon and cook until crispy.
- Remove the bacon from the pot and set aside.
- In the same pot, add the seasoned beef cubes and cook until browned on all sides.
- Remove the beef from the pot and set aside.
- In the same pot, add the diced onion and carrots and cook until softened.
- Add the minced garlic and cook for an additional minute.
- Stir in the tomato paste and cook for another minute.
- Add the beef and bacon back into the pot.
- Pour in the red wine and beef broth.
- Add the bouquet garni and bring to a simmer.
- Cover the pot and let it simmer for 2 hours, stirring occasionally.
- After 2 hours, add the pearl onions and mushrooms to the pot.
- Continue to simmer for an additional hour, or until the beef is tender.
- Remove the bouquet garni and discard.
- Taste and adjust seasoning with salt and pepper if needed.
- Garnish with chopped parsley before serving.

4. Cooking Implements Preparation:
- Large Dutch oven or heavy-bottomed pot
- Kitchen twine
- Cutting board
- Chef's knife
- Wooden spoon
- Measuring cups and spoons
- Bowls for prepped ingredients
- Tongs for handling meat
- Ladle for serving
- Serving dishes for the final dish.
python
dish2 = loaded_model.predict({"recipe": "Okonomiyaki", "customer_count": "12"})

print(dish2[0])

Ingredients:
- 2 cups all-purpose flour
- 2 teaspoons baking powder
- 1/2 teaspoon salt
- 2 eggs
- 1 1/2 cups water
- 1/2 head cabbage, thinly sliced
- 1/2 cup green onions, thinly sliced
- 1/2 cup carrots, grated
- 1/2 cup red bell pepper, thinly sliced
- 1/2 cup cooked shrimp, chopped
- 1/2 cup cooked bacon, chopped
- 1/2 cup pickled ginger, chopped
- 1/2 cup tenkasu (tempura flakes)
- 1/2 cup mayonnaise
- 1/4 cup okonomiyaki sauce
- 1/4 cup katsuobushi (dried bonito flakes)
- Vegetable oil for cooking

Preparation Techniques:
1. In a large mixing bowl, combine the flour, baking powder, and salt.
2. In a separate bowl, beat the eggs and water together.
3. Slowly pour the egg mixture into the flour mixture, stirring until well combined.
4. Set the batter aside to rest for 10 minutes.
5. Thinly slice the cabbage, green onions, and red bell pepper.
6. Grate the carrots.
7. Chop the cooked shrimp, bacon, and pickled ginger.
8. Prepare the tenkasu, mayonnaise, okonomiyaki sauce, and katsuobushi.

Ingredient Staging:
1. Place the sliced cabbage, green onions, carrots, red bell pepper, shrimp, bacon, and pickled ginger in separate bowls.
2. Arrange the tenkasu, mayonnaise, okonomiyaki sauce, and katsuobushi in small dishes.
3. Set up a large griddle or non-stick pan for cooking the okonomiyaki.

Cooking Implements Preparation:
1. Make sure the griddle or pan is clean and dry.
2. Heat the griddle or pan over medium heat.
3. Have a spatula, tongs, and a large plate ready for flipping and serving the okonomiyaki.
4. Prepare a large plate or platter for serving the finished okonomiyaki.

Remember, mise-en-place is key to a successful dish. Make sure all ingredients are prepped and ready to go before starting the cooking process. Happy cooking!

结论

在本教程的最后一步,我们将使用我们的 LangChain 模型执行另一个预测。这次,我们将探索为 12 位顾客准备一道日本菜“大阪烧”的准备工作。这展示了模型在各种菜肴上的适应性和多功能性。

使用加载的模型进行附加预测

模型处理“大阪烧”的输入并输出详细的准备步骤。这包括列出配料、解释准备技术、指导配料准备以及详细说明所需的烹饪用具,展示了模型精确处理各种食谱的能力。

我们学到了什么

  • 模型的多功能性:本教程重点介绍了 LangChain 框架,用于组装基本 LLM 应用程序的组件,将特定的指令性提示链接到 Completions 风格的 LLM。
  • MLflow 在模型管理中的作用:LangChain 与 MLflow 的集成展示了有效的模型生命周期管理,从创建、记录到预测执行。

结语

本教程提供了一个富有洞察力的旅程,通过 LangChain 模型与 MLflow 结合用于烹饪准备的创建、管理和利用。它展示了 LangChain 在复杂场景中的实际应用和适应性。我们希望这次经历能为您提供宝贵的知识,并鼓励您在您的项目中使用 LangChain 和 MLflow 进行进一步的探索和创新。编码愉快!

下一步是什么?

为了继续学习 MLflow 和 LangChain 在更复杂示例中的功能,我们鼓励您继续通过其他 LangChain 教程进行学习。