Spaces:
Paused
Paused
Add system message
Browse files
app.py
CHANGED
|
@@ -1,68 +1,96 @@
|
|
| 1 |
import openai
|
| 2 |
import tiktoken
|
|
|
|
|
|
|
| 3 |
import json
|
| 4 |
import os
|
| 5 |
|
| 6 |
openai.api_key = os.getenv('API_KEY')
|
|
|
|
| 7 |
|
| 8 |
-
def ask(question, history):
|
| 9 |
-
|
|
|
|
| 10 |
try:
|
| 11 |
response = openai.ChatCompletion.create(
|
| 12 |
model="gpt-3.5-turbo",
|
| 13 |
-
messages=forget_long_term(
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
)["choices"][0]["message"]["content"]
|
| 18 |
while response.startswith("\n"):
|
| 19 |
response = response[1:]
|
| 20 |
except Exception as e:
|
| 21 |
print(e)
|
| 22 |
response = 'Timeout! Please wait a few minutes and retry'
|
| 23 |
-
history = history + [response]
|
| 24 |
-
with open("dialogue.txt", "a", encoding='utf-8') as f:
|
| 25 |
-
f.write(json.dumps(history, ensure_ascii=False)+"\n")
|
| 26 |
return history
|
| 27 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
|
| 29 |
def forget_long_term(messages, max_num_tokens=4000):
|
| 30 |
-
def num_tokens_from_messages(messages, model="gpt-3.5-turbo"):
|
| 31 |
-
"""Returns the number of tokens used by a list of messages."""
|
| 32 |
-
try:
|
| 33 |
-
encoding = tiktoken.encoding_for_model(model)
|
| 34 |
-
except KeyError:
|
| 35 |
-
encoding = tiktoken.get_encoding("cl100k_base")
|
| 36 |
-
if model == "gpt-3.5-turbo": # note: future models may deviate from this
|
| 37 |
-
num_tokens = 0
|
| 38 |
-
for message in messages:
|
| 39 |
-
num_tokens += 4 # every message follows <im_start>{role/name}\n{content}<im_end>\n
|
| 40 |
-
for key, value in message.items():
|
| 41 |
-
num_tokens += len(encoding.encode(value))
|
| 42 |
-
if key == "name": # if there's a name, the role is omitted
|
| 43 |
-
num_tokens += -1 # role is always required and always 1 token
|
| 44 |
-
num_tokens += 2 # every reply is primed with <im_start>assistant
|
| 45 |
-
return num_tokens
|
| 46 |
-
else:
|
| 47 |
-
raise NotImplementedError(f"""num_tokens_from_messages() is not presently implemented for model {model}.
|
| 48 |
-
See https://github.com/openai/openai-python/blob/main/chatml.md for information on how messages are converted to tokens.""")
|
| 49 |
while num_tokens_from_messages(messages)>max_num_tokens:
|
| 50 |
-
messages
|
|
|
|
|
|
|
|
|
|
| 51 |
return messages
|
| 52 |
|
| 53 |
|
| 54 |
import gradio as gr
|
| 55 |
|
| 56 |
|
| 57 |
-
def
|
| 58 |
-
|
| 59 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
return "", history, response
|
| 61 |
|
| 62 |
|
| 63 |
with gr.Blocks() as demo:
|
| 64 |
|
| 65 |
-
|
| 66 |
['200字介绍一下凯旋门:'],
|
| 67 |
['网上购物有什么小窍门?'],
|
| 68 |
['补全下述对三亚的介绍:\n三亚位于海南岛的最南端,是'],
|
|
@@ -72,6 +100,12 @@ with gr.Blocks() as demo:
|
|
| 72 |
['polish the following statement for a paper: In this section, we perform case study to give a more intuitive demonstration of our proposed strategies and corresponding explanation.'],
|
| 73 |
]
|
| 74 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
gr.Markdown(
|
| 76 |
"""
|
| 77 |
朋友你好,
|
|
@@ -80,25 +114,31 @@ with gr.Blocks() as demo:
|
|
| 80 |
|
| 81 |
p.s. 响应时间和问题复杂程度相关,<del>一般能在10~20秒内出结果</del>用了新的api已经提速到大约5秒内了
|
| 82 |
""")
|
| 83 |
-
|
| 84 |
-
chatbot = gr.Chatbot()
|
| 85 |
-
state = gr.State([])
|
| 86 |
|
| 87 |
-
|
| 88 |
-
txt = gr.Textbox(show_label=False, placeholder="Enter text and press enter").style(container=False)
|
| 89 |
-
|
| 90 |
-
txt.submit(predict, [txt, state], [txt, state, chatbot])
|
| 91 |
|
| 92 |
-
with gr.
|
| 93 |
-
|
| 94 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
def clear(value):
|
| 99 |
-
return [], []
|
| 100 |
-
clr.click(clear, inputs=clr, outputs=[chatbot, state])
|
| 101 |
|
| 102 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
|
| 104 |
demo.launch()
|
|
|
|
| 1 |
import openai
|
| 2 |
import tiktoken
|
| 3 |
+
|
| 4 |
+
import datetime
|
| 5 |
import json
|
| 6 |
import os
|
| 7 |
|
| 8 |
openai.api_key = os.getenv('API_KEY')
|
| 9 |
+
openai.request_times = 0
|
| 10 |
|
| 11 |
+
def ask(question, history, behavior):
|
| 12 |
+
openai.request_times += 1
|
| 13 |
+
print(f"request times {openai.request_times}: {datetime.datetime.now()}")
|
| 14 |
try:
|
| 15 |
response = openai.ChatCompletion.create(
|
| 16 |
model="gpt-3.5-turbo",
|
| 17 |
+
messages=forget_long_term(
|
| 18 |
+
[
|
| 19 |
+
{"role":"system", "content":content}
|
| 20 |
+
for content in behavior
|
| 21 |
+
] + [
|
| 22 |
+
{"role":"user" if i%2==0 else "assistant", "content":content}
|
| 23 |
+
for i,content in enumerate(history + [question])
|
| 24 |
+
]
|
| 25 |
+
)
|
| 26 |
)["choices"][0]["message"]["content"]
|
| 27 |
while response.startswith("\n"):
|
| 28 |
response = response[1:]
|
| 29 |
except Exception as e:
|
| 30 |
print(e)
|
| 31 |
response = 'Timeout! Please wait a few minutes and retry'
|
| 32 |
+
history = history + [question, response]
|
|
|
|
|
|
|
| 33 |
return history
|
| 34 |
|
| 35 |
+
def num_tokens_from_messages(messages, model="gpt-3.5-turbo"):
|
| 36 |
+
"""Returns the number of tokens used by a list of messages."""
|
| 37 |
+
try:
|
| 38 |
+
encoding = tiktoken.encoding_for_model(model)
|
| 39 |
+
except KeyError:
|
| 40 |
+
encoding = tiktoken.get_encoding("cl100k_base")
|
| 41 |
+
if model == "gpt-3.5-turbo": # note: future models may deviate from this
|
| 42 |
+
num_tokens = 0
|
| 43 |
+
for message in messages:
|
| 44 |
+
num_tokens += 4 # every message follows <im_start>{role/name}\n{content}<im_end>\n
|
| 45 |
+
for key, value in message.items():
|
| 46 |
+
num_tokens += len(encoding.encode(value))
|
| 47 |
+
if key == "name": # if there's a name, the role is omitted
|
| 48 |
+
num_tokens += -1 # role is always required and always 1 token
|
| 49 |
+
num_tokens += 2 # every reply is primed with <im_start>assistant
|
| 50 |
+
return num_tokens
|
| 51 |
+
else:
|
| 52 |
+
raise NotImplementedError(f"""num_tokens_from_messages() is not presently implemented for model {model}.
|
| 53 |
+
See https://github.com/openai/openai-python/blob/main/chatml.md for information on how messages are converted to tokens.""")
|
| 54 |
|
| 55 |
def forget_long_term(messages, max_num_tokens=4000):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
while num_tokens_from_messages(messages)>max_num_tokens:
|
| 57 |
+
if messages[0]["role"]=="system" and not len(messages[0]["content"]>=max_num_tokens):
|
| 58 |
+
messages = messages[:1] + messages[2:]
|
| 59 |
+
else:
|
| 60 |
+
messages = messages[1:]
|
| 61 |
return messages
|
| 62 |
|
| 63 |
|
| 64 |
import gradio as gr
|
| 65 |
|
| 66 |
|
| 67 |
+
def to_md(content):
|
| 68 |
+
is_inside_code_block = False
|
| 69 |
+
count_backtick = 0
|
| 70 |
+
output_spans = []
|
| 71 |
+
for i in range(len(content)):
|
| 72 |
+
if content[i]=="\n" and not is_inside_code_block:
|
| 73 |
+
output_spans.append("<br>")
|
| 74 |
+
elif content[i]=="`":
|
| 75 |
+
count_backtick += 1
|
| 76 |
+
if count_backtick == 3:
|
| 77 |
+
count_backtick = 0
|
| 78 |
+
is_inside_code_block = not is_inside_code_block
|
| 79 |
+
output_spans.append(content[i])
|
| 80 |
+
else:
|
| 81 |
+
output_spans.append(content[i])
|
| 82 |
+
return "".join(output_spans)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def predict(question, history=[], behavior=[]):
|
| 86 |
+
history = ask(question, history, behavior)
|
| 87 |
+
response = [(to_md(history[i]),to_md(history[i+1])) for i in range(0,len(history)-1,2)]
|
| 88 |
return "", history, response
|
| 89 |
|
| 90 |
|
| 91 |
with gr.Blocks() as demo:
|
| 92 |
|
| 93 |
+
examples_txt = [
|
| 94 |
['200字介绍一下凯旋门:'],
|
| 95 |
['网上购物有什么小窍门?'],
|
| 96 |
['补全下述对三亚的介绍:\n三亚位于海南岛的最南端,是'],
|
|
|
|
| 100 |
['polish the following statement for a paper: In this section, we perform case study to give a more intuitive demonstration of our proposed strategies and corresponding explanation.'],
|
| 101 |
]
|
| 102 |
|
| 103 |
+
examples_bhv = [
|
| 104 |
+
"你现在是一位贴心的心理咨询师,会为我提供耐心的解答。",
|
| 105 |
+
"你现在是一名无神论者,不信奉任何宗教。",
|
| 106 |
+
f"You are a helpful assistant. Today is {datetime.date.today()}.",
|
| 107 |
+
]
|
| 108 |
+
|
| 109 |
gr.Markdown(
|
| 110 |
"""
|
| 111 |
朋友你好,
|
|
|
|
| 114 |
|
| 115 |
p.s. 响应时间和问题复杂程度相关,<del>一般能在10~20秒内出结果</del>用了新的api已经提速到大约5秒内了
|
| 116 |
""")
|
|
|
|
|
|
|
|
|
|
| 117 |
|
| 118 |
+
behavior = gr.State([])
|
|
|
|
|
|
|
|
|
|
| 119 |
|
| 120 |
+
with gr.Column(variant="panel"):
|
| 121 |
+
with gr.Row().style(equal_height=True):
|
| 122 |
+
with gr.Column(scale=0.85):
|
| 123 |
+
bhv = gr.Textbox(show_label=False, placeholder="输入你想让ChatGPT扮演的人设").style(container=False)
|
| 124 |
+
with gr.Column(scale=0.15, min_width=0):
|
| 125 |
+
button_set = gr.Button("Set")
|
| 126 |
+
gr.Examples(examples=examples_bhv, inputs=bhv)
|
| 127 |
+
bhv.submit(fn=lambda x:(x,[x]), inputs=[bhv], outputs=[bhv, behavior])
|
| 128 |
+
button_set.click(fn=lambda x:(x,[x]), inputs=[bhv], outputs=[bhv, behavior])
|
| 129 |
|
| 130 |
+
|
| 131 |
+
state = gr.State([])
|
|
|
|
|
|
|
|
|
|
| 132 |
|
| 133 |
+
with gr.Column(variant="panel"):
|
| 134 |
+
chatbot = gr.Chatbot()
|
| 135 |
+
txt = gr.Textbox(show_label=False, placeholder="输入你想让ChatGPT回答的问题").style(container=False)
|
| 136 |
+
with gr.Row():
|
| 137 |
+
button_gen = gr.Button("Submit")
|
| 138 |
+
button_clr = gr.Button("Clear")
|
| 139 |
+
gr.Examples(examples=examples_txt, inputs=txt)
|
| 140 |
+
txt.submit(predict, [txt, state, behavior], [txt, state, chatbot])
|
| 141 |
+
button_gen.click(fn=predict, inputs=[txt, state, behavior], outputs=[txt, state, chatbot])
|
| 142 |
+
button_clr.click(fn=lambda :([],[]), inputs=None, outputs=[chatbot, state])
|
| 143 |
|
| 144 |
demo.launch()
|