如何在Python中添加'消息历史'到基于llama-index的GPT-3

ztigrdn8  于 2023-08-07  发布在  Python
关注(0)|答案(1)|浏览(163)

我对使用llama-index库来训练GPT-3以及通过标准API使用ChatGPT(都是在Python中)还是相当陌生的。我注意到,标准ChatGPT API我可以简单地执行以下代码,让ChatGPT获取消息历史作为上下文:

message_history=[]
completion = openai.ChatCompletion.create(model="gpt-3.5-turbo",messages=message_history)

字符串
现在我正在使用llama-index库在更具体的上下文上训练GPT-3,但是我不知道如何让模型考虑message_history以及,这里是我目前正在编写的一个代码,我不知道如何实现message history:

def construct_index(directory_path):
    # set maximum input size
    max_input_size = 4096
    # set number of output tokens
    num_outputs = 2000
    # set maximum chunk overlap
    max_chunk_overlap = 20
    # set chunk size limit
    chunk_size_limit = 600 

    # define prompt helper
    prompt_helper = PromptHelper(max_input_size, num_outputs, max_chunk_overlap, chunk_size_limit=chunk_size_limit)
    # define LLM
    llm_predictor = LLMPredictor(llm=OpenAI(temperature=0.5, model_name="text-ada-001", max_tokens=num_outputs))
    # define context (dataset)
    documents = SimpleDirectoryReader(directory_path).load_data()
    # transform context to index format
    service_context = ServiceContext.from_defaults(llm_predictor=llm_predictor, prompt_helper=prompt_helper)
    index = GPTSimpleVectorIndex.from_documents(documents, service_context=service_context)
    # important: index are are like map, has latitutdes and logntitudes to indicate how each city (texts) are close to each other
    index.save_to_disk("index.json")
    return index

index = GPTSimpleVectorIndex.load_from_disk("index.json")
dbutils.widgets.text("user_input", "user: ")
response = index.query(dbutils.widgets.get("user_input"),response_mode='compact')
print("Response: ", response.response)

ltskdhd1

ltskdhd11#

我在使用Llama索引库使用GPT3.5 Turbo时遇到了类似的问题。什么解决了我的问题是ChatMessage内置对象从openai库。我使用chatengine在ChatMessage类型的“消息”列表中发送我的查询沿着我的对话上下文。聊天引擎文档可以在这里找到:
https://gpt-index.readthedocs.io/en/latest/examples/chat_engine/chat_engine_openai.html
我将系统消息、查询和GPT的响应存储在消息历史中,以维护对话历史。
尝试通过以下方式加载“index.json”文件:

storage_context = StorageContext.from_defaults(persist_dir=".")
    index = load_index_from_storage(storage_context)

字符串
然后像这样存储您的输入:

messages.append(ChatMessage(role="user", content=query))


现在使用chatengine()查询,如下所示:

chat_engine = index.as_chat_engine()
    response = chat_engine.chat(query, messages)


你会在response.response找到你的答案。

相关问题