Spaces:
Runtime error
Runtime error
File size: 2,333 Bytes
5a3180a b48578c 5a3180a |
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 |
import gradio as gr
import openai
import json
from pymongo import MongoClient
# Initialize MongoDB client
client = MongoClient("mongodb+srv://gradio-test:jiheng@cluster0.dvxynte.mongodb.net/?retryWrites=true&w=majority")
db = client['test']
collection = db['gradio']
def get_saved_data():
saved_data = collection.find({}, {"_id": 0, "question": 1, "system_message": 1})
options = [json.dumps(item) for item in saved_data]
return options
def chat_with_gpt(question, api_key, temperature, system_message):
openai.api_key = api_key
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": system_message},
{"role": "user", "content": question}
],
temperature=temperature
)
assistant_reply = response['choices'][0]['message']['content']
return f"{assistant_reply}"
def save_to_mongodb(question, system_message):
collection.insert_one({"question": question, "system_message": system_message})
return "Saved to MongoDB."
def update_textboxes(selected_data):
print(selected_data)
select_json = json.loads(selected_data)
print(select_json['question'], select_json['system_message'])
return select_json['question'], select_json['system_message']
with gr.Blocks() as app:
saved_data_dropdown = gr.Dropdown(get_saved_data(), label="Select Saved Data")
question = gr.Textbox(lines=2, placeholder="What's your question?", label="Question")
api_key = gr.Textbox(lines=1, placeholder="Your OpenAI API Key", label="API Key")
temperature = gr.Slider(minimum=0, maximum=1, step=0.01, value=0.7, label="Temperature")
system_message = gr.Textbox(lines=1, placeholder="System Message (Optional)", value="You are a helpful assistant.", label="System Message")
with gr.Row():
chat_btn = gr.Button("Chat with GPT")
save_btn = gr.Button("Share to community")
output = gr.Textbox(label="Result", interactive=False)
chat_btn.click(chat_with_gpt, inputs=[question, api_key, temperature, system_message], outputs=output)
save_btn.click(save_to_mongodb, inputs=[question, system_message], outputs=output)
saved_data_dropdown.select(update_textboxes, inputs=[saved_data_dropdown], outputs=[question, system_message])
app.launch()
|