开发也能看懂的大模型:LangChain库简介

513 阅读4分钟

LangChain 是一个强大的 Python 和 JavaScript 开源库,用于构建与大语言模型(LLMs)集成的应用程序。它提供了灵活的工具和模块,帮助开发者快速开发聊天机器人、问答系统、文档检索和任务自动化等基于 LLM 的应用。


核心理念

LangChain 的设计基于以下两个核心思想:

  1. 语言模型与周边组件结合:语言模型擅长生成和理解文本,但需要结合工具(如数据库、搜索引擎)才能高效解决复杂任务。
  2. 以链式结构完成复杂任务:将任务分解为多个步骤,每个步骤使用语言模型或其他工具来完成,最后组合成完整的解决方案。

模块介绍

LangChain 的主要模块如下:

1. Prompt 模块

  • 用于设计与模型交互的提示(prompt)。

  • 提供模板化支持,可以动态插入变量。

  • 示例

    from langchain.prompts import PromptTemplate
    
    template = "Translate the following text to French: {text}"
    prompt = PromptTemplate(input_variables=["text"], template=template)
    prompt_text = prompt.format(text="Hello, how are you?")
    print(prompt_text)  # 输出: Translate the following text to French: Hello, how are you?
    

2. LLM 模块

  • 支持集成多种语言模型(如 OpenAI、Hugging Face 等)。

  • 提供统一的接口调用模型,简化模型切换。

  • 示例

from langchain_openai import OpenAI

# 配置 API Key 方式 1: 环境变量
# import os
# os.environ["OPENAI_API_KEY"] = "your-openai-api-key"

# 配置 API Key 方式 2: 直接传递参数
llm = OpenAI(model_name="text-davinci-003", temperature=0.7, openai_api_key="your-openai-api-key")
response = llm("What is the capital of France?")
print(response)

3. Chains 模块

  • 将多个步骤组合成链式结构(Chain)。

  • 支持简单链(单步任务)和复杂链(多步任务)。

  • 示例

    from langchain.chains import LLMChain
    from langchain.prompts import PromptTemplate
    
    prompt = PromptTemplate(input_variables=["question"], template="What is {question}?")
    llm_chain = LLMChain(llm=llm, prompt=prompt)
    
    result = llm_chain.run(question="the capital of France")
    print(result)  # 输出: Paris
    

4. Agents 模块

  • 构建动态决策系统,语言模型可以选择工具来完成任务。

  • 支持集成工具,如搜索引擎、API 调用、计算器等。

  • 示例

    from langchain.agents import initialize_agent, Tool
    from langchain.tools import Calculator
    
    tools = [Tool(name="calculator", func=Calculator().run, description="Perform calculations")]
    agent = initialize_agent(tools, llm, agent="zero-shot-react-description")
    
    response = agent.run("What is 25 multiplied by 4?")
    print(response)  # 输出: 100
    

5. Memory 模块

  • 为对话引入记忆功能,使模型能够记住用户上下文。

  • 支持短期记忆(临时会话)和长期记忆(持久存储)。

  • 示例

    from langchain.chains import ConversationChain
    from langchain.memory import ConversationBufferMemory
    
    memory = ConversationBufferMemory()
    conversation = ConversationChain(llm=llm, memory=memory)
    
    response1 = conversation.predict(input="Hello!")
    response2 = conversation.predict(input="What is my name?")
    print(response1, response2)
    

6. Document Loaders 和 Retrieval 模块

  • 用于加载和检索文档内容。

  • 支持多种文档格式(PDF、HTML、数据库)。

  • 可结合向量数据库(如 Pinecone、Weaviate)实现知识检索。

  • 示例

    from langchain.document_loaders import TextLoader
    
    loader = TextLoader("sample.txt")
    documents = loader.load()
    print(documents)  # 输出: 文档内容
    

应用场景

  1. 智能问答系统

    • 集成知识库,构建具有上下文记忆的问答机器人。
    • 示例:客户支持、企业内部问答系统。
  2. 自动化任务处理

    • 通过 Agents 结合外部工具完成复杂任务,如数据分析、API 调用。
  3. 文本生成与增强

    • 使用 Prompt 模块设计生成模板,实现文本翻译、摘要和润色等。
  4. 文档检索与信息提取

    • 构建基于向量搜索的系统,用于从大量文档中检索关键内容。

优势

  • 模块化设计:各模块独立又可协作,方便扩展。
  • 多模型支持:兼容不同的 LLM,切换方便。
  • 工具集成:可与第三方工具和库深度整合,扩展功能强大。
  • 开发效率高:预置了许多常用组件,开发复杂应用时更加快捷。

学习建议

  1. 从基础模块入手:先熟悉 Prompt 和 LLM 模块。
  2. 动手实践案例:构建简单的问答系统或自动化工具链。
  3. 逐步集成工具:学习 Agents 和 Memory,尝试加入外部工具。
  4. 文档阅读和社区支持:LangChain 文档详细,且社区活跃,及时获取帮助。

案例:文本润色

1. 安装依赖

确保已安装 LangChain 和 OpenAI 库:

pip install langchain openai

2. 代码实现

from langchain.prompts import PromptTemplate
from langchain.llms import OpenAI

# 初始化 OpenAI 模型(需要设置你的 OpenAI API 密钥)
llm = OpenAI(model_name="text-davinci-003", temperature=0.7)

# 定义 Prompt 模板
template = """
Please rewrite the following text to make it more professional and polished:
{text}
"""

# 创建 PromptTemplate 对象
prompt = PromptTemplate(input_variables=["text"], template=template)

# 示例输入文本
input_text = "I think we should try to make our product better. It's not very good right now."

# 格式化 Prompt
formatted_prompt = prompt.format(text=input_text)

# 调用模型进行生成
response = llm(formatted_prompt)

# 输出结果
print("输入文本:", input_text)
print("润色后的文本:", response)

运行结果示例

输入文本:

I think we should try to make our product better. It's not very good right now.

润色后的文本:

I believe we should focus on improving our product as its current state does not meet expectations.