构建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 天前
专题:2025AI产业全景洞察报告:企业应用、技术突破与市场机遇|附920+份报告PDF、数据、可视化模板汇总下载
大数据·人工智能·pdf
吴佳浩1 天前
Langchain 浅出
python·langchain·llm
lumi.1 天前
Vue + Element Plus 实现AI文档解析与问答功能(含详细注释+核心逻辑解析)
前端·javascript·vue.js·人工智能
m0_650108241 天前
InstructBLIP:面向通用视觉语言模型的指令微调技术解析
论文阅读·人工智能·q-former·指令微调的视觉语言大模型·零样本跨任务泛化·通用视觉语言模型
金融小师妹1 天前
基于NLP语义解析的联储政策信号:强化学习框架下的12月降息概率回升动态建模
大数据·人工智能·深度学习·1024程序员节
AKAMAI1 天前
提升 EdgeWorker 可观测性:使用 DataStream 设置日志功能
人工智能·云计算
银空飞羽1 天前
让Trae CN SOLO自主发挥,看看能做出一个什么样的项目
前端·人工智能·trae
cg50171 天前
基于 Bert 基本模型进行 Fine-tuned
人工智能·深度学习·bert
Dev7z1 天前
基于Matlab图像处理的EAN条码自动识别系统设计与实现
图像处理·人工智能
Curvatureflight1 天前
GPT-4o Realtime 之后:全双工语音大模型如何改变下一代人机交互?
人工智能·语言模型·架构·人机交互