本文主要是介绍How to upload a file into existing OpenAI assistant?,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题意:如何将文件上传到现有的 OpenAI 助手中?
问题背景:
While using the Assistant API by OpenAI in python, how do I upload a new file into an existing assistant?
在使用 OpenAI 的 Python Assistant API 时,如何将新文件上传到现有助手中?
The documentations shows how to upload files in assistant creation time:
文档中展示了如何在助手创建时上传文件:
# Upload a file with an "assistants" purpose
file = client.files.create(file=open("knowledge.pdf", "rb"),purpose='assistants'
)# Add the file to the assistant
assistant = client.beta.assistants.create(instructions="You are a customer support chatbot. Use your knowledge base to best respond to customer queries.",model="gpt-4-1106-preview",tools=[{"type": "retrieval"}],file_ids=[file.id]
)
How do I add a new file/files into the existing assistant, which I retrieved in code as:
“如何将新文件添加到现有助手中,我在代码中检索到的助手为:”
client = OpenAI(api_key=api_key)assistant = client.beta.assistants.retrieve(assistant_id=assistant_id)
问题解决:
from openai import OpenAIassistant_id = ''
api_key = ''
file_path = 'all_questions.json'def upload_file_to_existing_assistant(api_key, assistant_id, file_path):# Initialize OpenAI client with the API keyclient = OpenAI(api_key=api_key)# Upload a file to OpenAIwith open(file_path, 'rb') as file:uploaded_file = client.files.create(file=file, purpose='assistants')# Add the uploaded file to the assistantclient.beta.assistants.files.create(assistant_id=assistant_id, file_id=uploaded_file.id)print(f"File '{file_path}' uploaded and added to the assistant with ID: {assistant_id}")# Example usage
upload_file_to_existing_assistant(api_key, assistant_id, file_path)
Here is an explanation of the different steps for clarity:
“这里是不同步骤的解释,以便更清晰理解:”
-
First we establish connection with OpenAI API and create a client
“首先,我们建立与 OpenAI API 的连接并创建一个客户端。”
-
Then we upload file to OpenAI. (Note: you can see all your uploaded files in the "Files" tab under OpenAI developer platform
“然后我们将文件上传到 OpenAI。(注意:你可以在 OpenAI 开发者平台的“文件”标签下查看所有已上传的文件。)”
-
Finally, we link file to assistant using FileID
“最后,我们使用 FileID 将文件链接到助手。”
这篇关于How to upload a file into existing OpenAI assistant?的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!