gpt4 book ai didi

python - 如何将 langchain 文档转换回字符串?

转载 作者:行者123 更新时间:2023-12-02 22:47:43 24 4
gpt4 key购买 nike

我用 langchain 库构建了一个分割器函数,可以分割一系列 python 文件。在代码中的另一点,我需要将这些文档转换回 python 代码。只是我不知道该怎么做

def index_repo(repo_url):

os.environ['OPENAI_API_KEY'] = ""

contents = []
fileextensions = [
".py", ]


print('cloning repo')
repo_dir = get_repo(repo_url)

file_names = []

for dirpath, dirnames, filenames in os.walk(repo_dir):
for file in filenames:
if file.endswith(tuple(fileextensions)):
file_names.append(os.path.join(dirpath, file))
try:
with open(os.path.join(dirpath, file), "r", encoding="utf-8") as f:
contents.append(f.read())

except Exception as e:
pass


# chunk the files
text_splitter = RecursiveCharacterTextSplitter.from_language(language=Language.PYTHON, chunk_size=5000, chunk_overlap=0)
texts = text_splitter.create_documents(contents)

return texts, file_names

最佳答案

尝试替换这个:

    texts = text_splitter.create_documents(contents)

这样:

    texts = text_splitter.split_text(contents)

您提供的代码使用 create_documents 方法创建一个 Document 对象(这是一个列表对象,其中每个项目都是包含两个键的字典:page_content:字符串元数据:字典)。使用 split_text 方法会将 RecursiveCharacterTextSplitter 中的每个 block 作为一个项目放入 texts 列表中。

希望这有帮助!

关于python - 如何将 langchain 文档转换回字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77025853/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com