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'}]}]}
- 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.