main code

mail@pastecode.io avatar
unknown
plain_text
2 months ago
4.2 kB
9
Indexable
Never
from time import sleep
from fastapi.responses import FileResponse
from packaging import version
import openai
from openai import OpenAI
from fastapi import FastAPI, HTTPException, Request
from pydantic import BaseModel
import asyncio
import json
import time
import uvicorn
from fastapi.staticfiles import StaticFiles
from datetime import datetime
from tickets import insert_ticket
 
# Change with your Assistant ID and OpenAI API Key
CHATBOT_ASSISTANT_ID = ""
OPENAI_API_KEY = ""
 
# Check OpenAI version is correct
required_version = version.parse("1.1.1")
current_version = version.parse(openai.__version__)
 
# Check if the OpenAI version is compatible
if current_version < required_version:
    raise ValueError(f"Error: OpenAI version {openai.__version__} is less than the required version 1.1.1")
else:
    print("OpenAI version is compatible.")
 
# Create FastAPI app
app = FastAPI()
 
# Initialize OpenAI client
client = OpenAI(api_key=OPENAI_API_KEY)
 
# Request Model for Chat
class ChatRequest(BaseModel):
    thread_id: str
    message: str
 
# Function to create a ticket
def create_ticket(name, cellphone, email, object):
    todays_date = datetime.now().strftime('%d-%m-%Y')
    insert_ticket(name, cellphone, email, object, todays_date)
    return "Ticket inserted correctly"
 
# Dictionary of available functions
available_functions = {
    "create_ticket": create_ticket
}
 
# Start conversation thread
@app.get('/start')
async def start_conversation():
    print("Starting a new conversation...")
    thread = client.beta.threads.create()
    print(f"New thread created with ID: {thread.id}")
    return {"thread_id": thread.id}
 
# Generate response
@app.post('/chat')
async def chat(chat_request: ChatRequest):
    thread_id = chat_request.thread_id
    user_input = chat_request.message
 
    if not thread_id:
        print("Error: Missing thread_id")
        raise HTTPException(status_code=400, detail="Missing thread_id")
 
    print(f"Received message: {user_input} for thread ID: {thread_id}")
    timeinit = time.time()
    client.beta.threads.messages.create(thread_id=thread_id, role="user", content=user_input)
 
    run = client.beta.threads.runs.create(thread_id=thread_id, assistant_id=CHATBOT_ASSISTANT_ID)
    end = False
    request_problem = False
    while not end:
        run_status = client.beta.threads.runs.retrieve(thread_id=thread_id, run_id=run.id)
        print(f"Run status: {run_status.status}")
        if run_status.status == 'completed' or run_status.status == "cancelled" or run_status.status == "expired":
            end = True
            if run_status.status == "cancelled" or run_status.status == "expired":
                request_problem = True
        elif run_status.status == "requires_action":
            tool_calls = run_status.required_action.submit_tool_outputs.tool_calls
            tool_outputs = []
            for tool_call in tool_calls:
                function_name = tool_call.function.name
                function_to_call = available_functions[function_name]
                function_args = json.loads(tool_call.function.arguments)
 
                # Call and passing the parameters generated by the assistant
                function_response = function_to_call(**function_args)
                tool_outputs.append({"tool_call_id": tool_call.id, "output": function_response})
            client.beta.threads.runs.submit_tool_outputs(thread_id=thread_id, run_id=run.id, tool_outputs=tool_outputs)
        elif run_status.status == "failed":
            print(run.last_error)
            end = True
            request_problem = True
 
        await asyncio.sleep(1)  # Using asyncio.sleep instead of time.sleep
 
    if not request_problem:
        messages = client.beta.threads.messages.list(thread_id=thread_id)
        response = messages.data[0].content[0].text.value
        # print elapsed seconds
        print(f"Elapsed time: {time.time() - timeinit}")
        print(f"Assistant response: {response}")
    else:
         response = "OpenAI request error"
    return {"response": response}
 
# Run the FastAPI app
if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8001)
Leave a Comment