umangchaudhry commited on
Commit
7289133
·
1 Parent(s): a11305b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +41 -22
app.py CHANGED
@@ -1,29 +1,48 @@
1
  import gradio as gr
2
  import openai
 
 
3
 
4
- def generate_code(api_key, prompt):
5
- openai.api_key = api_key
6
 
7
- response = openai.Completion.create(
8
- engine="text-davinci-002",
9
- prompt=prompt,
10
- max_tokens=100,
11
- n=1,
12
- stop=None,
13
- temperature=0.5,
14
- )
 
 
 
15
 
16
- return response.choices[0].text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
- if __name__ == "__main__":
19
- api_key_input = gr.inputs.Textbox(lines=1, label="OpenAI API Key", type="password")
20
- prompt_input = gr.inputs.Textbox(lines=5, label="Prompt")
21
- output = gr.outputs.Textbox(label="Generated Code")
22
 
23
- gr.Interface(
24
- fn=generate_code,
25
- inputs=[api_key_input, prompt_input],
26
- outputs=output,
27
- title="OpenAI Code Generator",
28
- description="Generate code using OpenAI's GPT-4 model. Enter your API key and a prompt, and let the AI write code for you!",
29
- ).launch()
 
1
  import gradio as gr
2
  import openai
3
+ import random
4
+ import time
5
 
6
+ # Set up OpenAI API key
7
+ openai.api_key = "insert your API key here"
8
 
9
+ system_message = {"role": "system", "content": "You are a helpful assistant."}
10
+
11
+ with gr.Blocks() as demo:
12
+ chatbot = gr.Chatbot()
13
+ msg = gr.Textbox()
14
+ clear = gr.Button("Clear")
15
+
16
+ state = gr.State([])
17
+
18
+ def user(user_message, history):
19
+ return "", history + [[user_message, None]]
20
 
21
+ def bot(history, messages_history):
22
+ user_message = history[-1][0]
23
+ bot_message, messages_history = ask_gpt(user_message, messages_history)
24
+ messages_history += [{"role": "assistant", "content": bot_message}]
25
+ history[-1][1] = bot_message
26
+ time.sleep(1)
27
+ return history, messages_history
28
+
29
+ def ask_gpt(message, messages_history):
30
+ messages_history += [{"role": "user", "content": message}]
31
+ response = openai.ChatCompletion.create(
32
+ model="gpt-3.5-turbo",
33
+ messages=messages_history
34
+ )
35
+ return response['choices'][0]['message']['content'], messages_history
36
+
37
+ def init_history(messages_history):
38
+ messages_history = []
39
+ messages_history += [system_message]
40
+ return messages_history
41
+
42
+ msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(
43
+ bot, [chatbot, state], [chatbot, state]
44
+ )
45
 
46
+ clear.click(lambda: None, None, chatbot, queue=False).success(init_history, [state], [state])
 
 
 
47
 
48
+ demo.launch()