温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么使用llama Index训练pdf

发布时间:2023-03-28 14:48:55 来源:亿速云 阅读:224 作者:iii 栏目:开发技术

这篇文章主要介绍“怎么使用llama Index训练pdf”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“怎么使用llama Index训练pdf”文章能帮助大家解决问题。

llama Index是什么

怎么使用llama Index训练pdf

LlamaIndex 是您的外部数据和 LLM 之间的一个简单、灵活的接口。它以易于使用的方式提供了以下工具:

为您现有的数据源和数据格式(API、PDF、文档、SQL 等)提供数据连接器

为您的非结构化和结构化数据提供索引,以便与 LLM 一起使用。这些索引有助于抽象出情境学习的常见样板和痛点:

  • 以易于访问的格式存储上下文以便快速插入。

  • 当上下文太大时处理提示限制(例如 Davinci 的 4096 个标记)。

  • 处理文本拆分。

  • 为用户提供查询索引(输入提示)并获得知识增强输出的界面。

  • 为您提供全面的工具集,权衡成本和性能。

这里只是LlamaIndex应用的冰山一角,还可以挖掘更多好玩的功能

下面让我一步步来教你如何实现

第一步:安装依赖

requirements.txt
Flask==2.2.3
Flask-Cors==3.0.10
langchain==0.0.115
llama-index==0.4.30
PyPDF2==3.0.1

我们需要部署一个web服务,这里我使用了Flask,你也可以使用fastapi 或者django实现。其次我们使用llama-index作为索引进行pdf查询。

第二步:训练数据和构建索引的server

index_server.py
import os
import pickle
# 这里可以换成你自己的key,但是最好不要上传到github上
os.environ['OPENAI_API_KEY'] = ""
from multiprocessing import Lock
from multiprocessing.managers import BaseManager
from llama_index import SimpleDirectoryReader, GPTSimpleVectorIndex, Document
index = None
stored_docs = {}
lock = Lock()
# 保存index的json文件
index_name = "./index.json"
# 保存文档的pkl文件 用于保存文档的id和文本,这样客户端就可以查询到文档的列表了
pkl_name = "stored_documents.pkl"
def initialize_index():
    """初始化index,如果已经存在index,就使用已经训练好的index,否则就创建一个新的index"""
    global index, stored_docs
    with lock:
        if os.path.exists(index_name):
            """使用已经训练好的index"""
            index = GPTSimpleVectorIndex.load_from_disk(index_name)
        else:
            """使用GPTSimpleVectorIndex创建一个新的index 这里是llama_index的一个bug,如果你不传入一个空的list,就会报错 """
            index = GPTSimpleVectorIndex([])
            index.save_to_disk(index_name)
        if os.path.exists(pkl_name):
            with open(pkl_name, "rb") as f:
                stored_docs = pickle.load(f)
def query_index(query_text):
    """查询index 根据你查询的文本,返回一个response"""
    global index
    response = index.query(query_text)
    return response
def insert_into_index(doc_file_path, doc_id=None):
    """将文档插入到index中,插入的文档可以是一个文件,也可以是一个字符串,
    如果doc_id不为空,就使用doc_id,否则就使用文件名作为doc_id"""
    global index, stored_docs
    document = SimpleDirectoryReader(input_files=[doc_file_path]).load_data()[0]
    if doc_id is not None:
        document.doc_id = doc_id
    # Keep track of stored docs -- llama_index doesn't make this easy
    stored_docs[document.doc_id] = document.text[0:200]  # only take the first 200 chars
    with lock:
        index.insert(document)
        index.save_to_disk(index_name)
        with open(pkl_name, "wb") as f:
            pickle.dump(stored_docs, f)
    return
def get_documents_list():
    """查询保存的文档列表,返回一个list"""
    global stored_doc
    documents_list = []
    for doc_id, doc_text in stored_docs.items():
        documents_list.append({"id": doc_id, "text": doc_text})
    return documents_list
if __name__ == "__main__":
    # 初始化index, 如果已经存在index,就使用已经训练好的index,否则就创建一个新的index
    print("initializing index...")
    initialize_index()
    # 启动服务器,监听5602端口
    manager = BaseManager(('127.0.0.1', 5602), b'123456')
    # 注册使用到的函数,这样客户端就可以调用这些函数了
    manager.register('query_index', query_index)
    manager.register('insert_into_index', insert_into_index)
    manager.register('get_documents_list', get_documents_list)
    server = manager.get_server()
    print("server started...")
    server.serve_forever()

注意上面的OPENAI_API_KEY需要修改为你自己的,否则执行initialize_index函数会提示报错

最后,成功启动

$ python index_server.py
initializing index...
server started...

关于“怎么使用llama Index训练pdf”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注亿速云行业资讯频道,小编每天都会为大家更新不同的知识点。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI