构建LangChain应用程序的示例代码:14、使用LangChain、GPT和Activeloop的Deep Lake来处理代码库

使用LangChain、GPT和Activeloop的Deep Lake来处理代码库

在本教程中

我们将使用Langchain + Activeloop的Deep Lake与GPT一起分析LangChain本身的代码库。

设计

准备数据:

  • 使用langchain_community.document_loaders.TextLoader上传所有Python项目文件。我们将称这些文件为文档。
  • 使用langchain_text_splitters.CharacterTextSplitter将所有文档拆分为块。
  • 使用langchain.embeddings.openai.OpenAIEmbeddingslangchain_community.vectorstores.DeepLake将块嵌入并上传到DeepLake。

问答:

  • 构建一个由langchain.chat_models.ChatOpenAIlangchain.chains.ConversationalRetrievalChain组成的链。
  • 准备问题。
  • 运行链以获取答案。

实现

集成准备

我们需要为外部服务设置密钥并安装必要的Python库。

python 复制代码
!python3 -m pip install --upgrade langchain deeplake openai

设置OpenAI嵌入、Deep Lake多模态向量存储API并进行身份验证。

有关Deep Lake的完整文档,请访问 Activeloop文档API参考

python 复制代码
import os
from getpass import getpass

os.environ["OPENAI_API_KEY"] = getpass("请输入OpenAI密钥")

如果您想创建自己的数据集并发布,请对Deep Lake进行身份验证。您可以在 Activeloop平台 上获取API密钥。

python 复制代码
activeloop_token = getpass("Activeloop Token:")
os.environ["ACTIVELOOP_TOKEN"] = activeloop_token

准备数据

加载所有仓库文件。这里我们假设此笔记本是作为langchain fork的一部分下载的,并且我们处理的是langchain repo的Python文件。

python 复制代码
from langchain_community.document_loaders import TextLoader

root_dir = "../../../../../libs"
docs = []

for dirpath, dirnames, filenames in os.walk(root_dir):
    for file in filenames:
        if file.endswith(".py") and "*venv/" not in dirpath:
            try:
                loader = TextLoader(os.path.join(dirpath, file), encoding="utf-8")
                docs.extend(loader.load_and_split())
            except Exception:
                pass

print(f"文档数量:{len(docs)}")

然后,将文件分块。

python 复制代码
from langchain_text_splitters import CharacterTextSplitter

text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
texts = text_splitter.split_documents(docs)
print(f"块的数量:{len(texts)}")

然后嵌入块并上传到DeepLake。

这可能需要几分钟时间。

python 复制代码
from langchain_openai import OpenAIEmbeddings

embeddings = OpenAIEmbeddings()
python 复制代码
from langchain_community.vectorstores import DeepLake

username = ""

db = DeepLake.from_documents(
    texts, embeddings, dataset_path=f"hub://{username}/langchain-code", overwrite=True
)

可选:您也可以使用Deep Lake的托管张量数据库作为托管服务,并在那里运行查询。

python 复制代码
from langchain_community.vectorstores import DeepLake

db = DeepLake.from_documents(
    texts, embeddings, dataset_path=f"hub://{username}/langchain-code", runtime={"tensor_db": True}
)

问答

首先加载数据集,构建检索器,然后构建对话链。

python 复制代码
db = DeepLake(
    dataset_path=f"hub://{username}/langchain-code",
    read_only=True,
    embedding=embeddings,
)
python 复制代码
retriever = db.as_retriever()
retriever.search_kwargs["distance_metric"] = "cos"
retriever.search_kwargs["fetch_k"] = 20
retriever.search_kwargs["maximal_marginal_relevance"] = True
retriever.search_kwargs["k"] = 20

您也可以使用Deep Lake过滤器指定用户定义的函数。

python 复制代码
def filter(x):
    # 基于源代码过滤
    if "something" in x["text"].data()["value"]:
        return False

# 打开下面的自定义过滤
retriever.search_kwargs['filter'] = filter
python 复制代码
from langchain.chains import ConversationalRetrievalChain
from langchain_openai import ChatOpenAI

model = ChatOpenAI(
    model_name="gpt-3.5-turbo-0613"
)

qa = ConversationalRetrievalChain.from_llm(model, retriever=retriever)
python 复制代码
questions = [
    "类层次结构是什么?",
    "哪些类是从Chain类派生的?",
    "LangChain有哪些类型的检索器?",
]

chat_history = []
qa_dict = {}

for question in questions:
    result = qa({"question": question, "chat_history": chat_history})
    chat_history.append((question, result["answer"]))
    qa_dict[question] = result["answer"]
    print(f"-> 问题:{question} \n")
    print(f"答案:{result['answer']} \n")
python 复制代码
print(qa_dict)
python 复制代码
print(qa_dict["类层次结构是什么?"])
print(qa_dict["哪些类是从Chain类派生的?"])
print(qa_dict["LangChain有哪些类型的检索器?"])

总结

本教程介绍了如何结合使用LangChain、GPT和Deep Lake来分析和理解代码库。通过上传Python项目文件,将其拆分为块,并使用OpenAI的嵌入技术上传到Deep Lake,我们构建了一个问答系统,能够对代码库进行深入分析并回答问题。这个过程不仅展示了代码分析的自动化能力,还体现了AI技术在提升开发效率和代码质量方面的潜力。

相关推荐
盛寒24 分钟前
N元语言模型 —— 一文讲懂!!!
人工智能·语言模型·自然语言处理
weixin_1772972206931 分钟前
家政小程序开发——AI+IoT技术融合,打造“智慧家政”新物种
人工智能·物联网
Jay Kay44 分钟前
ReLU 新生:从死亡困境到强势回归
人工智能·数据挖掘·回归
Blossom.1181 小时前
使用Python和Flask构建简单的机器学习API
人工智能·python·深度学习·目标检测·机器学习·数据挖掘·flask
无声旅者1 小时前
AI 模型分类全解:特性与选择指南
人工智能·ai·ai大模型
Grassto2 小时前
Cursor Rules 使用
人工智能
MYH5162 小时前
深度学习在非线性场景中的核心应用领域及向量/张量数据处理案例,结合工业、金融等领域的实际落地场景分析
人工智能·深度学习
Lilith的AI学习日记2 小时前
什么是预训练?深入解读大模型AI的“高考集训”
开发语言·人工智能·深度学习·神经网络·机器学习·ai编程
聚客AI2 小时前
PyTorch玩转CNN:卷积操作可视化+五大经典网络复现+分类项目
人工智能·pytorch·神经网络
程序员岳焱2 小时前
深度剖析:Spring AI 与 LangChain4j,谁才是 Java 程序员的 AI 开发利器?
java·人工智能·后端