为自己的 PDF 构建公共 GPT

Building public GPTs for own PDFs

提问人:dbeings 提问时间:11/12/2023 更新时间:11/12/2023 访问量:116

问:

我尝试通过上传 PDF 在 OpenAI 上创建 GPT。它在UI上运行良好,并且能够回答问题。但是当我将链接发送给某个人时,他们需要是 ChatGPT plus 用户才能使用它。因此,我尝试使用API并将助手与ChatComplete端点链接在一起,但这一直给我带来错误。我还尝试将文件 ID 传递给 chatComplete,但没有奏效。以下是相关的代码片段 - 请指导合适的方法。

file = client.files.create(
  file=open("mydoc.pdf", "rb"),
  purpose='assistants'
)

assistant = client.beta.assistants.create(
  instructions="You will answer question on the pdf document that I have uploaded. ... ",
  model="gpt-4-1106-preview",
  tools=[{"type": "retrieval"}],
  file_ids=[file.id]
)

while True:
    user_input = input("You: ") #followed by exit code


#using assitant with chat. Commented this to use file id with chatCompletion
'''
response = client.assistants.chat(
        assistant_id=assistant_id,
        messages=[{"role": "user", "content": user_input}]
    )
'''
#using file id with ChatCompletion
response = client.ChatCompletion.create(
        model="gpt-4-1106-preview", 
        messages=[
            {"role": "system", "content": "You will answer question on the pdf document that I have uploaded. ..."},
            {"role": "user", "content": user_input}
        ],
        file=file.id
    )

问候 dbeings

openai-api 聊天-gpt-4

评论


答:

0赞 dbeings 11/12/2023 #1

这得到了排序。我混淆了 chatCompletion 和 Assistants API,因为我关注的是 chatGPT,而不是 API 文档:)API 文档提供了有关助手使用情况的详细信息,但不清楚提取线程执行后的结束消息。以下是有效的代码:

import openai

api_key = 'sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
client = openai.Client(api_key=api_key)

# Upload a file with an "assistants" purpose
file = client.files.create(
  file=open("mydoc.pdf", "rb"),
  purpose='assistants'
)

# Add the file to the assistant
assistant = client.beta.assistants.create(
  instructions="You will answer question on the pdf document that I have uploaded.....",
  model="gpt-4-1106-preview",
  tools=[{"type": "retrieval"}],
  file_ids=[file.id]
)

assistant_id = assistant.id

while True:
    # Get user input
    user_input = input("You: ")

    # Break the loop if the user types 'exit'
    if user_input.lower() == 'exit':
        break
    
    thread = client.beta.threads.create(
        messages=[
            {
                "role": "user",
                "content": user_input,
                "file_ids": [file.id]
            }
        ]
    )

    run = client.beta.threads.runs.create(
        thread_id=thread.id,
        assistant_id=assistant_id
    )
    
    while run.status != "completed":
        run = client.beta.threads.runs.retrieve(
            thread_id=thread.id,
            run_id=run.id
        )
    
    print("Searching...")
    messages = client.beta.threads.messages.list(
        thread_id=thread.id
    )

    message_content = messages.data[0].content[0].text.value
    
    print("Assistant:", message_content)