构建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技术在提升开发效率和代码质量方面的潜力。

相关推荐
虫无涯2 小时前
LangSmith:大模型应用开发的得力助手
人工智能·langchain·llm
算家计算2 小时前
DeepSeek-R1论文登《自然》封面!首次披露更多训练细节
人工智能·资讯·deepseek
weiwenhao3 小时前
关于 nature 编程语言
人工智能·后端·开源
神经星星3 小时前
训练成本29.4万美元,DeepSeek-R1登Nature封面,首个通过权威期刊同行评审的主流大模型获好评
人工智能
神州问学3 小时前
【AI洞察】别再只想着“让AI听你话”,人类也需要学习“适应AI”!
人工智能
DevUI团队3 小时前
🚀 MateChat V1.8.0 震撼发布!对话卡片可视化升级,对话体验全面进化~
前端·vue.js·人工智能
聚客AI3 小时前
🎉7.6倍训练加速与24倍吞吐提升:两项核心技术背后的大模型推理优化全景图
人工智能·llm·掘金·日新计划
黎燃3 小时前
当 YOLO 遇见编剧:用自然语言生成技术把“目标检测”写成“目标剧情”
人工智能
算家计算3 小时前
AI教母李飞飞团队发布最新空间智能模型!一张图生成无限3D世界,元宇宙越来越近了
人工智能·资讯
掘金一周3 小时前
Flutter Riverpod 3.0 发布,大规模重构下的全新状态管理框架 | 掘金一周 9.18
前端·人工智能·后端