Error Creating Thread in Azure OpenAI Assistant – “Failed to create file operation”

I am trying to use the Azure OpenAI Assistant with the file search tool. I successfully uploaded the files and created a vector store, but I encounter a 500 – server_error when attempting to create a thread. Here is the relevant part of my code:

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from azure_client import configure_azure_client, create_assistant, create_vector_store, upload_files
from openai import AssistantEventHandler
import time

# Initialize FastAPI
app = FastAPI()
filename = "incidentes_ficticios2.json"

# Configure Azure OpenAI client
print("10. Configuring Azure OpenAI client...")
client = configure_azure_client()

# Create assistant
print("11. Creating assistant...")
assistant = create_assistant(client)

# Create vector store
print("12. Creating vector store...")
vector_store = create_vector_store(client)

# Upload files to vector store
print("13. Uploading files to vector store...")
file_batch = upload_files(client, vector_store, [filename])

# Polling to ensure files are processed
print("14. Checking file processing status...")
while True:
    file_batch = client.beta.vector_stores.file_batches.retrieve(file_batch.id)
    if file_batch.status == 'completed':
        print("15. Files successfully processed.")
        break
    elif file_batch.status == 'failed':
        raise HTTPException(status_code=500, detail="File processing failed.")
    print("15a. Waiting for files to process...")
    time.sleep(5)

# Update assistant with vector store
print("16. Updating assistant with vector store...")
assistant = client.beta.assistants.update(
    assistant_id=assistant.id,
    tool_resources={"file_search": {"vector_store_ids": [vector_store.id]}},
)
print("17. Assistant updated with vector store.")

# Define request model
class QueryRequest(BaseModel):
    query: str

# Event handler class
class EventHandler(AssistantEventHandler):
    def __init__(self):
        self.response = None

    def on_text_created(self, text):
        print("18. Assistant created text:", text)
        self.response = text

    def on_tool_call_created(self, tool_call):
        print("19. Tool call created:", tool_call.type)

    def on_message_done(self, message):
        print("20. Assistant processed message:", message.content)

# Endpoint to query assistant
@app.post("/query")
async def query_assistant(request: QueryRequest):
    try:
        print("21. Query received:", request.query)

        # Create message file
        print("22. Creating message file...")
        try:
            message_file = client.files.create(
                file=open(filename, "rb"), purpose="assistants"
            )
            print("23. Message file created:", message_file.id)
        except Exception as e:
            print("23a. Error creating message file:", str(e))
            raise

        # Read file content for debugging
        try:
            with open(filename, "r") as f:
                file_content = f.read()
                print("23b. File content:", file_content[:1000])
        except Exception as e:
            print("23c. Error reading file for debugging:", str(e))
            raise

        # Check assistant and vector store resources
        print("23d. Assistant resources:", assistant.tool_resources)
        print("23e. Vector store ID:", vector_store.id)

        # Create thread with user message
        print("24. Creating thread...")
        try:
            thread = client.beta.threads.create(
                messages=[
                    {
                        "role": "user",
                        "content": request.query,
                        "attachments": [
                            {"file_id": message_file.id, "tools": [{"type": "file_search"}]}
                        ],
                    }
                ]
            )
            print("25. Thread created:", thread.id)
        except Exception as e:
            print("25a. Error creating thread:", str(e))
            print("25b. Message details:", {
                "role": "user",
                "content": request.query,
                "attachments": [
                    {"file_id": message_file.id, "tools": [{"type": "file_search"}]}
                ],
            })
            raise

        # Initialize event handler to capture events
        event_handler = EventHandler()

        # Execute assistant stream
        print("26. Executing assistant stream...")
        try:
            with client.beta.threads.runs.stream(
                thread_id=thread.id,
                assistant_id=assistant.id,
                instructions=request.query,
                event_handler=event_handler,
            ) as stream:
                stream.until_done()
        except Exception as e:
            print("26a. Error executing assistant stream:", str(e))
            raise

        # Check if assistant provided a response
        if event_handler.response is None:
            print("27. No response from assistant.")
            raise HTTPException(status_code=500, detail="No response from assistant")

        print("28. Assistant response:", event_handler.response)
        return {"response": event_handler.response}
    except Exception as e:
        print("29. Error processing query:", str(e))
        raise HTTPException(status_code=500, detail=str(e))

# Start Uvicorn server
if __name__ == "__main__":
    print("30. Starting Uvicorn server...")
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)

Error Logs:

23a. Erro ao criar thread: Error code: 500 - {'error': {'message': 'Failed to create file operation.', 'type': 'server_error', 'param': None, 'code': None}}
23b. Detalhes da mensagem: {'role': 'user', 'content': 'tem bug?', 'attachments': [{'file_id': 'assistant-YHnvnwCKLeGoKe7ySvGqUDqP', 'tools': [{'type': 'file_search'}]}]}
27. Erro ao processar consulta: Error code: 500 - {'error': {'message': 'Failed to create file operation.', 'type': 'server_error', 'param': None, 'code': None}}

I have confirmed that the file content is correct and the vector store has been updated successfully. What could be causing this issue when creating a thread? Any insights or suggestions would be appreciated.

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