Project

General

Profile

Feature #3602

Add file support to OpenAI assistant

Added by Ram Kordale 6 months ago. Updated 3 months ago.

Status:
Closed
Priority:
High
Assignee:
Start date:
06/06/2024
Due date:
% Done:

100%

Estimated time:

Description

OpenAI assistants API can take files as inputs. change set_prompt_mods to take an additional input:

"file_urls" : ["<url1>", "<url2>", ...]"

<urlk> will be Google Cloud Storage URL.

Ensure that these files are associated with the assistant when it is created. Example code below.

import openai
from openai import OpenAI

  1. 1. OpenAI Setup
    client = OpenAI(api_key="YOUR_API_KEY")
  1. 2. File Preparation and Upload (Do this once for initial setup)
    def upload_files(file_paths):
    file_ids = []
    for path in file_paths:
    with open(path, "rb") as file:
    file_response = client.files.create(file=file, purpose="assistants")
    file_ids.append(file_response.id)
    return file_ids
  1. Replace with your actual file paths
    file_paths = ["your_document1.txt", "your_document2.pdf", ...]
    uploaded_file_ids = upload_files(file_paths)
  1. 3. Create Assistant
    assistant = client.beta.assistants.create(
    model="gpt-3.5-turbo-1106",
    instructions="You are a helpful assistant. Answer questions using the provided files. If the answer is not in the files, say you couldn't find it.",
    tools=[{"type": "file_search"}],
    file_ids=uploaded_file_ids # Attach files
    )
  1. 4. Create Thread and Get User's Question
    thread = client.beta.threads.create()

while True:
user_input = input("Ask your question: ")

  1. 5. Add Message to Thread
    client.beta.threads.messages.create(
    thread_id=thread.id,
    role="user",
    content=user_input
    )
  1. 6. Run the Assistant
    run = client.beta.threads.runs.create(
    thread_id=thread.id,
    assistant_id=assistant.id
    )
  1. 7. Retrieve Assistant's Response
    while True:
    run_status = client.beta.threads.runs.retrieve(thread_id=thread.id, run_id=run.id)
    if run_status.status == 'completed':
    messages = client.beta.threads.messages.list(thread_id=thread.id)
    assistant_message = messages.data0.content0.text # Latest message
    print("Answer:", assistant_message.value)
    break
#1

Updated by Md Shahzar 6 months ago

  • Status changed from New to In Progress
#2

Updated by Md Shahzar 6 months ago

  • Status changed from In Progress to Resolved
  • % Done changed from 0 to 100
#3

Updated by Md Shahzar 5 months ago

  • Status changed from Resolved to Feedback
  • Assignee changed from Md Shahzar to Ram Kordale
#4

Updated by Ram Kordale 3 months ago

  • Status changed from Feedback to Closed

Also available in: Atom PDF