python-3.x - 在 ChatGPT OpenAI 中的 Langchain 和 ConversationChain() 中使用自定义 JSON 数据作为上下文

标签 python-3.x openai-api chatgpt-api langchain py-langchain

我有一个自定义 JSON 文件,该文件是从 Excel 工作表创建的,其中包含我希望我的问题所基于的某些数据,以及我需要 OpenAI 提供答案的数据。现在为此我有一段代码如下 -

s3 = boto3.client('s3')      # read from S3
obj = s3.get_object(Bucket='bucketname', Key='sample.xlsx')

data = obj['Body'].read()
df = pd.read_excel(io.BytesIO(data), sheet_name='randomsheetname')

df = df.to_dict("records")     # create JSON dataframe from sheetdata

response = openai.ChatCompletion.create(
     model="gpt-4",
     messages=[{
         "role": "system", "content": f"{prompt}. \n\nJSON file: {df}. \n\nAnswer:"
     }],
     temperature=0.5,
     max_tokens=500
)

为此,我能够获得对基于我提供给 openai.ChatCompletion.create() 的输入 JSON 文件的任何问题的答复

现在,如果我想跟踪我之前的对话并为 openai 提供上下文以根据同一对话线程中之前的问题回答问题,我必须使用 langchain。我在向 ChatOpenAI() 和 ConversationChain() 提供 JSON 数据集时遇到问题,因为我正在处理类似的事情。 (使用Python编写)

llm = ChatOpenAI(temperature=0.5, openai_api_key=api_key, model="gpt-4")
    conversation = ConversationChain(
        llm=llm, 
        prompt=prompt_template,
        verbose=True, 
        memory=memory,
        chain_type_kwargs=chain_type_kwargs
    )
    response = conversation.predict(input=prompt)
    

请帮忙。

最佳答案

我在langchain中使用以下方法。

ChatOpenAI 在 langchain 中的简单用例。

from langchain.chat_models import ChatOpenAI
from langchain.schema import (
    AIMessage,
    HumanMessage,
    SystemMessage
)
llm = ChatOpenAI(temperature=0.9,model_name="gpt-3.5-turbo", max_tokens = 2048)
system_text = "You are helpfull assistant that tells jokes"
human_prompt = "Tell a joke"

output_answer = llm.predict_messages([SystemMessage(content = system_text), HumanMessage(content=human_prompt)])
print(output_answer.content)

由于您需要提供文档,您可能还可以查看 ConversationalRetrievalChain 或其他检索选项,因为它们允许将文档上下文存储在向量存储中,这对于优化 token 计数很有用。

qa = ConversationalRetrievalChain.from_llm(
    ChatOpenAI(temperature=0, model="gpt-4"),
    vectorstore.as_retriever()
)
chat_history = []
query = "What did the president say about Ketanji Brown Jackson"
result = qa({"question": query, "chat_history": chat_history})

关于python-3.x - 在 ChatGPT OpenAI 中的 Langchain 和 ConversationChain() 中使用自定义 JSON 数据作为上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76175798/

相关文章:

openai-api - 为 Langchain 中的 create_pandas_dataframe_agent 添加内存

php - Laravel OpenAI 客户端无法处理列表结果

python - 如何将 urllib 响应写入文件

python - 从私有(private) Git 存储库进行 Pip 安装,在 Git URL 中使用个人访问 token

algorithm - 直观理解 Adam 优化器

python - “模块”对象不可调用。执行 AI 文件时出错

python - 使用 GPT API 创建多消息对话

python-3.x - PyTorch 中的 nn.functional() 与 nn.sequential() 之间是否存在计算效率差异

python-3.x - 如何按顺序用 np 数组替换 pandas 数据帧的选定行?

reinforcement-learning - 为什么 Stable-Baselines3 evaluate_policy() 函数永远不会完成/完成?