OpenAI API Assistant does not find file on the uploaded files

I am not able to get the Assistant API to find an uploaded file in the uploaded files. Could you please provide specific code to correct my code as I am quite poor coder?

I have tried to read API documentation but I cannot understand what the entire code should look lik and I do not fully understand how different element are linked to each other. Hence, a full code would be appreciated.

def initialize_openai_resources(file_path, model, analysis_type, user_prompt):
    """
    Initializes OpenAI client, uploads a file, creates an assistant, and initializes a thread based on predefined settings.

    Parameters:
    - file_path: Path to the file to be uploaded.
    - model: Model type for the assistant (e.g., 'gpt-3.5-turbo').

    Returns:
    - A dictionary containing the assistant and thread objects.
    """
    client = get_openai_client()
    print("OpenAI API key loaded successfully.n")

    # Upload a file
    with open(file_path, 'rb') as file_data:
        my_file = client.files.create(
            file=file_data,
            purpose="assistants"
        )
    print(f"File uploaded successfully with ID: {my_file.id}n")

    # Create Vector Store and upload a file there
    vector_store = client.beta.vector_stores.create(file_ids=[my_file.id])
    print(f"Vector store created successfully with ID: {vector_store.id}n")
    print(f"File with ID {my_file.id} has been successfully attached to Vector store with ID {vector_store.id}n")

    if analysis_type == 'thematic':
        instructions = ta_instruction.format(user_prompt=user_prompt)
    elif analysis_type == 'content':
        instructions = ca_instruction.format(user_prompt=user_prompt)
    elif analysis_type == 'grounded':
        instructions = gt_instruction.format(user_prompt=user_prompt)
    else:
        raise ValueError("Unsupported analysis type")

    # Create an Assistant
    my_assistant = client.beta.assistants.create(
        instructions=instructions,
        name="QDA-GPT",
        tools=[{"type": "file_search"}],
        model=model,
        tool_resources={"file_search": {"vector_store_ids": [vector_store.id]}}
    )
    print(f"Assistant created successfully with ID: {my_assistant.id}n")

    # Create a Thread
    my_thread = client.beta.threads.create()

    # Validate that everything has been initialized successfully.
    print(f"Thread created successfully with ID: {my_thread.id}n")

    return {'assistant': my_assistant, 'file':my_file, 'thread': my_thread, 'vector_store': vector_store,}





def get_openai_response(content, assistant_id, thread_id):
    """
    Sends content to ChatGPT using an existing assistant and thread, and retrieves the response.

    Parameters:
    - content: The user's input to be sent to ChatGPT.
    - assistant_id: The ID of the initialized assistant.
    - thread_id: The ID of the initialized thread.

    Returns:
    - The response from ChatGPT as a string, or "No response." if no response is retrieved.
    """
    client = get_openai_client()
    print("OpenAI API key loaded successfully. Sending content to OpenAi Assistant.n")


    try:

        # Send message to the thread
        my_thread_message = client.beta.threads.messages.create(
            thread_id=thread_id,
            role="user",
            content=content
        )
        if not my_thread_message or not my_thread_message.content:
            return "Message creation failed.", "Failure"
        print(f"Message sent to thread. Message ID: {my_thread_message.id}n")


        # Run the assistant
        my_run = client.beta.threads.runs.create(
            thread_id=thread_id,
            assistant_id=assistant_id,
        )
        print(f"Assistant run initiated. Run ID: {my_run.id}n")

        # Retrieve the Run status
        # Periodically retrieve the Run to check on its status to see if it has moved to completed
        print("Run status: in_progress", end="")
        sys.stdout.flush()  # Ensure "in_progress" is displayed immediately
        while my_run.status in ["queued", "in_progress"]:
            keep_retrieving_run = client.beta.threads.runs.retrieve(
                thread_id=thread_id,
                run_id=my_run.id
            )

            if keep_retrieving_run.status == "in_progress":
                print(".", end="")
                sys.stdout.flush()  # Print each dot immediately
                time.sleep(0.5)    # Increase/reduce this if necessary
            elif keep_retrieving_run.status == "completed":
                print("nRun status: completedn")

                # Retrieve the Messages added by the Assistant to the Thread
                all_messages = client.beta.threads.messages.list(
                    thread_id=thread_id
                )
                if not all_messages or not all_messages.data or not all_messages.data[0].content:
                    return "Response retrieval failed.", "Failure"

                response = all_messages.data[0].content[0].text.value

                print("------------------------------------------------------------n")
                print("Response retrieved successfully.n")
                print("Assistant response processed successfully.n")
                return response
            else:
                print(f"nRun status: {keep_retrieving_run.status}n")
                break

        return "Failed to retrieve a valid response from OpenAI.n"

    except Exception as e:
        print(f"An error occurred: {str(e)} n")
        return "Failed to retrieve a valid response from OpenAI.n"

New contributor

Markus Munter is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật