Edward commited on
Commit
6485a4b
·
1 Parent(s): 78a265d

通过文本长度限制每次提问的长度

Browse files
Files changed (2) hide show
  1. app.py +7 -13
  2. requirements.txt +1 -2
app.py CHANGED
@@ -1,11 +1,8 @@
1
  import openai
2
  import os
3
  import gradio as gr
4
- import tiktoken as tk
5
 
6
  openai.api_key = os.environ.get("OPENAI_API_KEY")
7
- # 定义tiktoken编码器
8
- encoding = tk.get_encoding("cl100k_base")
9
  # 定义提示词长度不能大于1024
10
  MAX_PROMPT_LENGTH = 1024
11
  # 提示词
@@ -14,13 +11,12 @@ prompt = """你是一个AI个人助手。你的回答需要满足以下要求:
14
  2. 回答限制在1000个字以内"""
15
 
16
 
17
- # 利用tiktoken校验提示词长度,防止提示词过长,方法返回Boolean值
18
- def check_prompt(question):
19
- check_len = len(encoding.encode(prompt)) + len(encoding.encode(question))
20
- if check_len > MAX_PROMPT_LENGTH:
21
  return False
22
- else:
23
- return True
24
 
25
 
26
  class Conversation:
@@ -31,10 +27,8 @@ class Conversation:
31
  self.messages.append({"role": "system", "content": self.prompt})
32
 
33
  def ask(self, question):
34
- # 校验提示词长度,若长度大于限制长度,则直接返回错误提示
35
- if not check_prompt(question):
36
- return "Error: The length of prompt is too long!"
37
-
38
  try:
39
  self.messages.append({"role": "user", "content": question})
40
  response = openai.ChatCompletion.create(
 
1
  import openai
2
  import os
3
  import gradio as gr
 
4
 
5
  openai.api_key = os.environ.get("OPENAI_API_KEY")
 
 
6
  # 定义提示词长度不能大于1024
7
  MAX_PROMPT_LENGTH = 1024
8
  # 提示词
 
11
  2. 回答限制在1000个字以内"""
12
 
13
 
14
+ # 校验提示词长度
15
+ def check_prompt_length(question):
16
+ text_length = len(prompt) + len(question)
17
+ if len(text_length) > MAX_PROMPT_LENGTH:
18
  return False
19
+ return True
 
20
 
21
 
22
  class Conversation:
 
27
  self.messages.append({"role": "system", "content": self.prompt})
28
 
29
  def ask(self, question):
30
+ if not check_prompt_length(question):
31
+ return "你的输入太长了,请将文本长度限制在900以内,请重新输入"
 
 
32
  try:
33
  self.messages.append({"role": "user", "content": question})
34
  response = openai.ChatCompletion.create(
requirements.txt CHANGED
@@ -1,2 +1 @@
1
- openai
2
- tiktoken
 
1
+ openai