军舰 commited on
Commit
e0c4e40
1 Parent(s): 070f95f

Add application file

Browse files
Files changed (2) hide show
  1. app.py +99 -0
  2. requirements.txt +3 -0
app.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 = "您是一名美食家,帮助别人了解美食的信息,回答要简洁有效并控制在100字左右。"
83
+
84
+ conv = Conversation(system_prompt_foodie, max_tokens=1024)
85
+
86
+ with gr.Blocks(title="ChatGPT 助手") as demo:
87
+ chatbot = gr.Chatbot(elem_id="chatbot")#.style(height=700)
88
+ msg = gr.Textbox(show_label=False).style(container=False)
89
+ clear = gr.Button("Clear")
90
+
91
+ def ask(message, chat_history):
92
+ bot_message = conv.ask(message)
93
+ chat_history.append((message, bot_message))
94
+ return "", chat_history
95
+
96
+ msg.submit(ask, [msg, chatbot], [msg, chatbot])
97
+ clear.click(lambda: conv.reset(), None, chatbot, queue=False)
98
+
99
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ openai
2
+ tiktoken
3
+