umangchaudhry commited on
Commit
da67f32
·
1 Parent(s): 83167a5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +40 -23
app.py CHANGED
@@ -1,31 +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.strip()
 
 
 
 
 
 
17
 
18
- def app(api_key, chatbot_prompt):
19
- generated_code = generate_code(api_key, chatbot_prompt)
20
- return f"Generated Code:\n{generated_code}"
 
 
 
 
21
 
22
- if __name__ == "__main__":
23
- api_key_input = gr.inputs.Textbox(lines=1, label="OpenAI API Key", type="password")
24
- chat_interface = gr.Chat(
25
- inputs=[api_key_input],
26
- title="OpenAI Code Generator",
27
- description="Generate code using OpenAI's GPT-4 model. Enter your API key and a prompt, and let the AI write code for you!",
28
- examples=[],
29
- fn=app,
30
  )
31
- chat_interface.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 = "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"
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()