Spaces:
Runtime error
Runtime error
Create app.py (#1)
Browse files- Create app.py (bffb14a83f86d8f1afca58704a30acbb410d22dc)
app.py
ADDED
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import openai
|
2 |
+
import gradio as gr
|
3 |
+
import csv
|
4 |
+
import os
|
5 |
+
|
6 |
+
MODEL = "gpt-3.5-turbo"
|
7 |
+
chat_history_file = "chat_history.csv"
|
8 |
+
|
9 |
+
openai.api_key = os.environ.get("OPENAI_API_KEY")
|
10 |
+
|
11 |
+
def generate_chat_response(input_text):
|
12 |
+
prompt = f"Conversation:\nUser: {input_text}\nAI:"
|
13 |
+
completion = openai.ChatCompletion.create(
|
14 |
+
model=MODEL,
|
15 |
+
max_tokens=3000,
|
16 |
+
n=1,
|
17 |
+
stop=None,
|
18 |
+
temperature=0.5,
|
19 |
+
messages=[{"role": "user", "content": "Hello!"}]
|
20 |
+
)
|
21 |
+
response = (completion.choices[0].message)
|
22 |
+
return render_template("talkgpt.html", response=response)
|
23 |
+
|
24 |
+
|
25 |
+
def chatbot_response(input_text):
|
26 |
+
# load chat history from file
|
27 |
+
chat_history = []
|
28 |
+
with open(chat_history_file, "r") as f:
|
29 |
+
reader = csv.reader(f)
|
30 |
+
for row in reader:
|
31 |
+
chat_history.append({"input": row[0], "output": row[1]})
|
32 |
+
|
33 |
+
# add current input to chat history
|
34 |
+
chat_history.append({"input": input_text, "output": ""})
|
35 |
+
|
36 |
+
# use OpenAI ChatCompletion model to generate a response
|
37 |
+
# based on the user's input text
|
38 |
+
response_text = generate_chat_response(input_text)
|
39 |
+
|
40 |
+
# add response to chat history
|
41 |
+
chat_history[-1]["output"] = response_text
|
42 |
+
|
43 |
+
# save chat history to file
|
44 |
+
with open(chat_history_file, "w") as f:
|
45 |
+
writer = csv.writer(f)
|
46 |
+
for row in chat_history:
|
47 |
+
writer.writerow([row["input"], row["output"]])
|
48 |
+
|
49 |
+
return response_text
|
50 |
+
|
51 |
+
chatbot_interface = gr.Interface(
|
52 |
+
fn=chatbot_response,
|
53 |
+
inputs=["text", gr.inputs.Voice()],
|
54 |
+
outputs=["text", gr.outputs.Voice()],
|
55 |
+
title="Chatbot",
|
56 |
+
description="Talk to the chatbot using text and speech inputs."
|
57 |
+
)
|
58 |
+
|
59 |
+
chatbot_interface.launch()
|