-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
128 lines (105 loc) · 4.33 KB
/
Copy pathmain.py
File metadata and controls
128 lines (105 loc) · 4.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
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
OPENAI_API_KEY = "" # tua api key da leggere preferibilmente da .evn
CHATBOT_ASSISTANT_ID = "" # tuo assistant id da leggere preferibilmente da .evn
# Check OpenAI version is correct
required_version = version.parse("1.1.1")
current_version = version.parse(openai.__version__)
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()
# Init client
client = OpenAI(api_key=OPENAI_API_KEY)
# Request Model for Chat
class ChatRequest(BaseModel):
thread_id: str
message: str
# Function prenota di esempio
def prenota(nome, numero_cel, riassunto_breve_chat):
print(f"Nome: {nome} Cell: {numero_cel} Riassunto: {riassunto_breve_chat}")
return "ok inserito correttamente"
# Lista di funzioni disponibili
available_functions = {
"prenota": prenota
}
# 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)
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}
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8001)