Spaces:
Runtime error
Runtime error
军舰 commited on
Commit ·
988d147
1
Parent(s): 456be22
add user set OpenAI API Key
Browse files
app.py
CHANGED
|
@@ -1,96 +1,32 @@
|
|
| 1 |
import os
|
| 2 |
import openai
|
| 3 |
-
import tiktoken
|
| 4 |
-
|
| 5 |
-
openai.api_key = os.getenv("OPENAI_API_KEY")
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
class Conversation:
|
| 9 |
-
def __init__(self, prompt, model="gpt-3.5-turbo", temperature=0.8, max_tokens=250):
|
| 10 |
-
self.prompt = prompt
|
| 11 |
-
self.model = model
|
| 12 |
-
self.temperature = temperature
|
| 13 |
-
self.max_tokens = max_tokens
|
| 14 |
-
|
| 15 |
-
self._init_messages()
|
| 16 |
-
|
| 17 |
-
def _init_messages(self):
|
| 18 |
-
self.messages = [{"role": "system", "content": self.prompt}]
|
| 19 |
-
|
| 20 |
-
def reset(self):
|
| 21 |
-
self._init_messages()
|
| 22 |
-
|
| 23 |
-
def ask(self, question, pprint=False):
|
| 24 |
-
self.messages.append({"role": "user", "content": question})
|
| 25 |
-
|
| 26 |
-
if self.num_tokens(self.messages, self.model) >= self.max_tokens:
|
| 27 |
-
if len(self.messages) > 3:
|
| 28 |
-
self.messages = self.messages[:1] + self.messages[3:] # remove the first user message
|
| 29 |
-
else:
|
| 30 |
-
return "Error: max tokens exceeded."
|
| 31 |
-
|
| 32 |
-
try:
|
| 33 |
-
response = openai.ChatCompletion.create(
|
| 34 |
-
model=self.model,
|
| 35 |
-
messages=self.messages
|
| 36 |
-
)
|
| 37 |
-
except Exception as e:
|
| 38 |
-
return e
|
| 39 |
-
|
| 40 |
-
if pprint:
|
| 41 |
-
print(f"tiktoken: {self.num_tokens(self.messages, self.model)}\ntokens: {response['usage']}")
|
| 42 |
-
|
| 43 |
-
assistant_message = response["choices"][0]["message"]["content"]
|
| 44 |
-
self.messages.append({"role": "assistant", "content": assistant_message})
|
| 45 |
-
|
| 46 |
-
return assistant_message
|
| 47 |
-
|
| 48 |
-
def num_tokens(self, messages, model):
|
| 49 |
-
"""Returns the number of tokens used by a list of messages."""
|
| 50 |
-
try:
|
| 51 |
-
encoding = tiktoken.encoding_for_model(model)
|
| 52 |
-
except KeyError:
|
| 53 |
-
print("Warning: model not found. Using cl100k_base encoding.")
|
| 54 |
-
encoding = tiktoken.get_encoding("cl100k_base")
|
| 55 |
-
if model == "gpt-3.5-turbo":
|
| 56 |
-
print("Warning: gpt-3.5-turbo may change over time. Returning num tokens assuming gpt-3.5-turbo-0301.")
|
| 57 |
-
return self.num_tokens(messages, model="gpt-3.5-turbo-0301")
|
| 58 |
-
elif model == "gpt-4":
|
| 59 |
-
print("Warning: gpt-4 may change over time. Returning num tokens assuming gpt-4-0314.")
|
| 60 |
-
return self.num_tokens(messages, model="gpt-4-0314")
|
| 61 |
-
elif model == "gpt-3.5-turbo-0301":
|
| 62 |
-
tokens_per_message = 4 # every message follows <|start|>{role/name}\n{content}<|end|>\n
|
| 63 |
-
tokens_per_name = -1 # if there's a name, the role is omitted
|
| 64 |
-
elif model == "gpt-4-0314":
|
| 65 |
-
tokens_per_message = 3
|
| 66 |
-
tokens_per_name = 1
|
| 67 |
-
else:
|
| 68 |
-
raise NotImplementedError(f"""num_tokens_from_messages() is not implemented for model {model}. See https://github.com/openai/openai-python/blob/main/chatml.md for information on how messages are converted to tokens.""")
|
| 69 |
-
num_tokens = 0
|
| 70 |
-
for message in messages:
|
| 71 |
-
num_tokens += tokens_per_message
|
| 72 |
-
for key, value in message.items():
|
| 73 |
-
num_tokens += len(encoding.encode(value))
|
| 74 |
-
if key == "name":
|
| 75 |
-
num_tokens += tokens_per_name
|
| 76 |
-
num_tokens += 3 # every reply is primed with <|start|>assistant<|message|>
|
| 77 |
-
return num_tokens
|
| 78 |
-
|
| 79 |
-
|
| 80 |
import gradio as gr
|
| 81 |
|
| 82 |
-
system_prompt_foodie = "您是一名美食家,帮助别人了解美食的
|
| 83 |
-
|
|
|
|
| 84 |
conv = Conversation(system_prompt_foodie, max_tokens=1024)
|
| 85 |
|
| 86 |
with gr.Blocks(title="ChatGPT 助手") as demo:
|
| 87 |
-
|
| 88 |
-
|
|
|
|
| 89 |
clear = gr.Button("Clear")
|
| 90 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
def ask(message, chat_history):
|
| 92 |
-
|
| 93 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
return "", chat_history
|
| 95 |
|
| 96 |
msg.submit(ask, [msg, chatbot], [msg, chatbot])
|
|
|
|
| 1 |
import os
|
| 2 |
import openai
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
import gradio as gr
|
| 4 |
|
| 5 |
+
system_prompt_foodie = """您是一名美食家,帮助别人了解美食的问题。您的回答需要满足以下要求:
|
| 6 |
+
1. 回答要使用中文。
|
| 7 |
+
2. 回答要控制在100字以内。"""
|
| 8 |
conv = Conversation(system_prompt_foodie, max_tokens=1024)
|
| 9 |
|
| 10 |
with gr.Blocks(title="ChatGPT 助手") as demo:
|
| 11 |
+
openai_api_key = gr.Textbox(label="OpenAI API Key")
|
| 12 |
+
chatbot = gr.Chatbot(elem_id="chatbot").style(height=500)
|
| 13 |
+
msg = gr.Textbox(show_label=False, placeholder="Please enter your question...").style(container=False)
|
| 14 |
clear = gr.Button("Clear")
|
| 15 |
|
| 16 |
+
def set_openai_api_key(openai_api_key):
|
| 17 |
+
openai.api_key = os.getenv("OPENAI_API_KEY")
|
| 18 |
+
if openai_api_key:
|
| 19 |
+
openai.api_key = openai_api_key
|
| 20 |
+
|
| 21 |
+
openai_api_key.change(set_openai_api_key, openai_api_key)
|
| 22 |
+
|
| 23 |
def ask(message, chat_history):
|
| 24 |
+
if openai.api_key is None:
|
| 25 |
+
chat_history.append((message, "Error: No OpenAI API Key found. Please enter your key in the cell above."))
|
| 26 |
+
else:
|
| 27 |
+
bot_message = conv.ask(message)
|
| 28 |
+
chat_history.append((message, bot_message))
|
| 29 |
+
|
| 30 |
return "", chat_history
|
| 31 |
|
| 32 |
msg.submit(ask, [msg, chatbot], [msg, chatbot])
|