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

相关推荐
deardao3 分钟前
【时序异常检测综述】十年回顾:深入研究时间序列异常检测
人工智能·机器学习·时间序列·事件检测
Axis tech6 分钟前
SenseGlove R1外骨骼手套专为机器人遥操作设计
人工智能
沫儿笙7 分钟前
弧焊机器人节气设备
人工智能·机器人
百锦再14 分钟前
Python实现开源AI模型引入及测试全过程
人工智能·python·ai·开源·aigc·模型·自然语言
咋吃都不胖lyh19 分钟前
详解 UCB 算法的置信区间与核心逻辑(通俗 + 公式 + 实例)
人工智能·算法·机器学习
造火箭20 分钟前
普通手机使用Open-AutoGLM 感受豆包AI 手机的体验
人工智能·智能手机
Mr.Lee jack21 分钟前
【torch.compile】PyTorch Dynamo 和 Inductor 编译流程
人工智能·pytorch·深度学习
浮不上来23 分钟前
人工兔优化算法(ARO)详解:原理、实现与应用
大数据·人工智能·机器学习·优化算法
Elastic 中国社区官方博客28 分钟前
Elastic 在 AWS re:Invent:总结一年在 agentic AI 创新中的合作
大数据·人工智能·elasticsearch·搜索引擎·云计算·全文检索·aws
IvorySQL31 分钟前
版本发布| IvorySQL 5.1 发布
数据库·人工智能·postgresql·开源