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

相关推荐
亲持红叶1 分钟前
GLU 变种:ReGLU 、 GEGLU 、 SwiGLU
人工智能·深度学习·神经网络·激活函数
说私域1 分钟前
线上协同办公时代:以开源AI大模型等工具培养网感,拥抱职业变革
人工智能·开源
群联云防护小杜3 分钟前
深度隐匿源IP:高防+群联AI云防护防绕过实战
运维·服务器·前端·网络·人工智能·网络协议·tcp/ip
摘星编程8 分钟前
构建智能客服Agent:从需求分析到生产部署
人工智能·需求分析·智能客服·agent开发·生产部署
不爱学习的YY酱11 分钟前
信息检索革命:Perplexica+cpolar打造你的专属智能搜索中枢
人工智能
whaosoft-1431 小时前
51c自动驾驶~合集7
人工智能
刘晓倩4 小时前
Coze智能体开发实战-多Agent综合实战
人工智能·coze
石迹耿千秋5 小时前
迁移学习--基于torchvision中VGG16模型的实战
人工智能·pytorch·机器学习·迁移学习
路人蛃8 小时前
通过国内扣子(Coze)搭建智能体并接入discord机器人
人工智能·python·ubuntu·ai·aigc·个人开发
Mr.小海8 小时前
常用 Benchmark 总结-GPT 4.1、GPT 4.5、DeepSeek模型
gpt