xl2533 commited on
Commit
67270bc
·
1 Parent(s): ebfba5a

add inital app

Browse files
Files changed (2) hide show
  1. __init__.py +1 -0
  2. app.py +135 -0
__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # -*-coding:utf-8 -*-
app.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import json
4
+ import requests
5
+
6
+ # Streaming endpoint
7
+ API_URL = "https://api.openai.com/v1/chat/completions" # os.getenv("API_URL") + "/generate_stream"
8
+
9
+
10
+ def predict(inputs, top_p, temperature, openai_api_key, chat_counter, chatbot=[],
11
+ history=[]): # repetition_penalty, top_k
12
+
13
+ payload = {
14
+ "model": "gpt-3.5-turbo",
15
+ "messages": [{"role": "user", "content": f"{inputs}"}],
16
+ "temperature": 1.0,
17
+ "top_p": 1.0,
18
+ "n": 1,
19
+ "stream": True,
20
+ "presence_penalty": 0,
21
+ "frequency_penalty": 0,
22
+ }
23
+
24
+ headers = {
25
+ "Content-Type": "application/json",
26
+ "Authorization": f"Bearer {openai_api_key}"
27
+ }
28
+
29
+ print(f"chat_counter - {chat_counter}")
30
+ if chat_counter != 0:
31
+ messages = []
32
+ for data in chatbot:
33
+ temp1 = {}
34
+ temp1["role"] = "user"
35
+ temp1["content"] = data[0]
36
+ temp2 = {}
37
+ temp2["role"] = "assistant"
38
+ temp2["content"] = data[1]
39
+ messages.append(temp1)
40
+ messages.append(temp2)
41
+ temp3 = {}
42
+ temp3["role"] = "user"
43
+ temp3["content"] = inputs
44
+ messages.append(temp3)
45
+ # messages
46
+ payload = {
47
+ "model": "gpt-3.5-turbo",
48
+ "messages": messages, # [{"role": "user", "content": f"{inputs}"}],
49
+ "temperature": temperature, # 1.0,
50
+ "top_p": top_p, # 1.0,
51
+ "n": 1,
52
+ "stream": True,
53
+ "presence_penalty": 0,
54
+ "frequency_penalty": 0,
55
+ }
56
+
57
+ chat_counter += 1
58
+
59
+ history.append(inputs)
60
+ print(f"payload is - {payload}")
61
+ # make a POST request to the API endpoint using the requests.post method, passing in stream=True
62
+ response = requests.post(API_URL, headers=headers, json=payload, stream=True)
63
+ # response = requests.post(API_URL, headers=headers, json=payload, stream=True)
64
+ token_counter = 0
65
+ partial_words = ""
66
+
67
+ counter = 0
68
+ for chunk in response.iter_lines():
69
+ if counter == 0:
70
+ counter += 1
71
+ continue
72
+ counter += 1
73
+ # check whether each line is non-empty
74
+ if chunk:
75
+ # decode each line as response data is in bytes
76
+ if len(json.loads(chunk.decode()[6:])['choices'][0]["delta"]) == 0:
77
+ break
78
+ # print(json.loads(chunk.decode()[6:])['choices'][0]["delta"]["content"])
79
+ partial_words = partial_words + json.loads(chunk.decode()[6:])['choices'][0]["delta"]["content"]
80
+ if token_counter == 0:
81
+ history.append(" " + partial_words)
82
+ else:
83
+ history[-1] = partial_words
84
+ chat = [(history[i], history[i + 1]) for i in range(0, len(history) - 1, 2)] # convert to tuples of list
85
+ token_counter += 1
86
+ yield chat, history, chat_counter # resembles {chatbot: chat, state: history}
87
+
88
+
89
+ def reset_textbox():
90
+ return gr.update(value='')
91
+
92
+
93
+ title = """<h1 align="center">🔥Finance ChatBot 🚀Streaming🚀</h1>"""
94
+ description = """Language models can be conditioned to act like dialogue agents through a conversational prompt that typically takes the form:
95
+ ```
96
+ User: <utterance>
97
+ Assistant: <utterance>
98
+ User: <utterance>
99
+ Assistant: <utterance>
100
+ ...
101
+ ```
102
+ In this app, you can explore the outputs of a gpt-3.5-turbo LLM.
103
+ """
104
+
105
+ with gr.Blocks(css="""#col_container {width: 1000px; margin-left: auto; margin-right: auto;}
106
+ #chatbot {height: 520px; overflow: auto;}""") as demo:
107
+ gr.HTML(title)
108
+ gr.HTML(
109
+ '''<center><img src="https://bit.ly/3gLdBN6" alt="Duplicate Space"></a>Duplicate the Space and run securely with your OpenAI API Key</center>''')
110
+ with gr.Column(elem_id="col_container"):
111
+ openai_api_key = gr.Textbox(type='password', label="Enter your OpenAI API key here")
112
+ chatbot = gr.Chatbot(elem_id='chatbot') # c
113
+ inputs = gr.Textbox(placeholder="Hi there!", label="Type an input and press Enter") # t
114
+ state = gr.State([]) # s
115
+ b1 = gr.Button()
116
+
117
+ # inputs, top_p, temperature, top_k, repetition_penalty
118
+ with gr.Accordion("Parameters", open=False):
119
+ top_p = gr.Slider(minimum=-0, maximum=1.0, value=1.0, step=0.05, interactive=True,
120
+ label="Top-p (nucleus sampling)", )
121
+ temperature = gr.Slider(minimum=-0, maximum=5.0, value=1.0, step=0.1, interactive=True,
122
+ label="Temperature", )
123
+ # top_k = gr.Slider( minimum=1, maximum=50, value=4, step=1, interactive=True, label="Top-k",)
124
+ # repetition_penalty = gr.Slider( minimum=0.1, maximum=3.0, value=1.03, step=0.01, interactive=True, label="Repetition Penalty", )
125
+ chat_counter = gr.Number(value=0, visible=False, precision=0)
126
+
127
+ inputs.submit(predict, [inputs, top_p, temperature, openai_api_key, chat_counter, chatbot, state],
128
+ [chatbot, state, chat_counter], )
129
+ b1.click(predict, [inputs, top_p, temperature, openai_api_key, chat_counter, chatbot, state],
130
+ [chatbot, state, chat_counter], )
131
+ b1.click(reset_textbox, [], [inputs])
132
+ inputs.submit(reset_textbox, [], [inputs])
133
+
134
+ # gr.Markdown(description)
135
+ demo.queue().launch(debug=True)