Spaces:
Runtime error
Runtime error
Updated code to use OpenAI
Browse files- app.py +75 -4
- requirements.txt +11 -0
app.py
CHANGED
@@ -1,7 +1,78 @@
|
|
1 |
import gradio as gr
|
2 |
|
3 |
-
|
4 |
-
|
5 |
|
6 |
-
|
7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import gradio as gr
|
2 |
|
3 |
+
import asyncio, httpx
|
4 |
+
import async_timeout
|
5 |
|
6 |
+
from loguru import logger
|
7 |
+
from typing import Optional, List
|
8 |
+
from pydantic import BaseModel
|
9 |
+
|
10 |
+
import os
|
11 |
+
from dotenv import load_dotenv
|
12 |
+
load_dotenv()
|
13 |
+
|
14 |
+
API_KEY = os.getenv("OPENAI_API_KEY")
|
15 |
+
|
16 |
+
class Message(BaseModel):
|
17 |
+
role: str
|
18 |
+
content: str
|
19 |
+
|
20 |
+
async def make_completion(messages:List[Message], nb_retries:int=3, delay:int=30) -> Optional[str]:
|
21 |
+
"""
|
22 |
+
Sends a request to the ChatGPT API to retrieve a response based on a list of previous messages.
|
23 |
+
"""
|
24 |
+
header = {
|
25 |
+
"Content-Type": "application/json",
|
26 |
+
"Authorization": f"Bearer {API_KEY}"
|
27 |
+
}
|
28 |
+
try:
|
29 |
+
async with async_timeout.timeout(delay=delay):
|
30 |
+
async with httpx.AsyncClient(headers=header) as aio_client:
|
31 |
+
counter = 0
|
32 |
+
keep_loop = True
|
33 |
+
while keep_loop:
|
34 |
+
logger.debug(f"Chat/Completions Nb Retries : {counter}")
|
35 |
+
try:
|
36 |
+
resp = await aio_client.post(
|
37 |
+
url = "https://api.openai.com/v1/chat/completions",
|
38 |
+
json = {
|
39 |
+
"model": "gpt-3.5-turbo",
|
40 |
+
"messages": messages
|
41 |
+
}
|
42 |
+
)
|
43 |
+
logger.debug(f"Status Code : {resp.status_code}")
|
44 |
+
if resp.status_code == 200:
|
45 |
+
return resp.json()["choices"][0]["message"]["content"]
|
46 |
+
else:
|
47 |
+
logger.warning(resp.content)
|
48 |
+
keep_loop = False
|
49 |
+
except Exception as e:
|
50 |
+
logger.error(e)
|
51 |
+
counter = counter + 1
|
52 |
+
keep_loop = counter < nb_retries
|
53 |
+
except asyncio.TimeoutError as e:
|
54 |
+
logger.error(f"Timeout {delay} seconds !")
|
55 |
+
return None
|
56 |
+
|
57 |
+
async def predict(input, history):
|
58 |
+
"""
|
59 |
+
Predict the response of the chatbot and complete a running list of chat history.
|
60 |
+
"""
|
61 |
+
history.append({"role": "user", "content": input})
|
62 |
+
response = await make_completion(history)
|
63 |
+
history.append({"role": "assistant", "content": response})
|
64 |
+
messages = [(history[i]["content"], history[i+1]["content"]) for i in range(0, len(history)-1, 2)]
|
65 |
+
return messages, history
|
66 |
+
|
67 |
+
"""
|
68 |
+
Gradio Blocks low-level API that allows to create custom web applications (here our chat app)
|
69 |
+
"""
|
70 |
+
with gr.Blocks() as demo:
|
71 |
+
logger.info("Starting Demo...")
|
72 |
+
chatbot = gr.Chatbot(label="WebGPT")
|
73 |
+
state = gr.State([])
|
74 |
+
with gr.Row():
|
75 |
+
txt = gr.Textbox(show_label=False, placeholder="Enter text and press enter").style(container=False)
|
76 |
+
txt.submit(predict, [txt, state], [chatbot, state])
|
77 |
+
|
78 |
+
demo.launch(server_port=8080)
|
requirements.txt
ADDED
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
fastapi==0.92.0
|
2 |
+
gradio==3.19.1
|
3 |
+
httpx==0.23.3
|
4 |
+
loguru==0.6.0
|
5 |
+
numpy==1.24.2
|
6 |
+
pydantic==1.10.5
|
7 |
+
python-dotenv==1.0.0
|
8 |
+
PyYAML==6.0
|
9 |
+
requests==2.28.2
|
10 |
+
six==1.16.0
|
11 |
+
uvicorn==0.20.0
|