leonsimon23 commited on
Commit
5599459
·
verified ·
1 Parent(s): c4da235

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +119 -91
app.py CHANGED
@@ -9,9 +9,10 @@ logging.basicConfig(level=logging.DEBUG)
9
  logger = logging.getLogger(__name__)
10
 
11
  class FastGPTChat:
12
- def __init__(self, api_key, base_url="https://api.fastgpt.in/api"):
13
  self.api_key = api_key
14
  self.base_url = base_url
 
15
  self.headers = {
16
  "Authorization": f"Bearer {api_key}",
17
  "Content-Type": "application/json"
@@ -23,87 +24,69 @@ class FastGPTChat:
23
 
24
  chat_id = str(uuid.uuid4())
25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
  # 准备请求数据
27
  data = {
28
  "chatId": chat_id,
29
- "stream": False,
30
  "detail": True,
31
- "model": "gpt-4o", # 指定使用 gpt-4 模型
32
- "messages": [
33
- {
34
- "role": "user",
35
- "content": message
36
- }
37
- ]
38
  }
39
 
40
  try:
41
- # 打印请求信息
42
- logger.debug(f"Request URL: {self.base_url}/v1/chat/completions")
43
- logger.debug(f"Request Headers: {json.dumps(self.headers, indent=2)}")
44
- logger.debug(f"Request Data: {json.dumps(data, indent=2)}")
45
-
46
- # 发送请求
47
  response = requests.post(
48
  f"{self.base_url}/v1/chat/completions",
49
  headers=self.headers,
50
  json=data,
 
51
  timeout=30
52
  )
53
 
54
- # 打印响应信息
55
- logger.debug(f"Response Status Code: {response.status_code}")
56
- logger.debug(f"Response Headers: {dict(response.headers)}")
57
- logger.debug(f"Response Content: {response.text}")
58
-
59
- # 检查响应状态
60
  if response.status_code != 200:
61
- error_msg = f"API Error: Status {response.status_code}, Response: {response.text}"
62
  logger.error(error_msg)
63
  chat_history.append((message, f"Error: {error_msg}"))
64
  return "", chat_history
65
 
66
- # 解析响应
67
- try:
68
- response_data = response.json()
69
- logger.debug(f"Parsed Response: {json.dumps(response_data, indent=2)}")
70
-
71
- # 检查是否有错误信息
72
- if "responseData" in response_data:
73
- for item in response_data["responseData"]:
74
- if "error" in item:
75
- error_msg = item["error"].get("message", "Unknown error")
76
- logger.error(f"API Error: {error_msg}")
77
- chat_history.append((message, f"Error: {error_msg}"))
78
- return "", chat_history
79
-
80
- if "choices" in response_data and len(response_data["choices"]) > 0:
81
- content = response_data["choices"][0]["message"]["content"]
82
- # 如果content是列表,提取文本内容
83
- if isinstance(content, list):
84
- text_contents = []
85
- for item in content:
86
- if isinstance(item, dict) and "text" in item:
87
- text_contents.append(item["text"].get("content", ""))
88
- ai_message = " ".join(text_contents)
89
- else:
90
- ai_message = content
91
-
92
- if not ai_message:
93
- ai_message = "No response generated from the API"
94
- logger.warning("Empty response content")
95
- else:
96
- ai_message = "No response generated from the API"
97
- logger.warning("No choices in response data")
98
-
99
- chat_history.append((message, ai_message))
100
- return "", chat_history
101
-
102
- except json.JSONDecodeError as e:
103
- error_msg = f"Failed to parse API response: {str(e)}"
104
- logger.error(error_msg)
105
- chat_history.append((message, f"Error: {error_msg}"))
106
- return "", chat_history
107
 
108
  except requests.exceptions.RequestException as e:
109
  error_msg = f"Request failed: {str(e)}"
@@ -115,41 +98,74 @@ def create_chat_interface(api_key):
115
  # 创建FastGPT聊天实例
116
  fastgpt_chat = FastGPTChat(api_key)
117
 
118
- # 创建Gradio界面
119
- with gr.Blocks(title="FastGPT Chat") as interface:
120
- gr.Markdown("# FastGPT Chat Interface (Using GPT-4o)")
121
-
122
- with gr.Row():
123
- api_key_input = gr.Textbox(
124
- label="API Key",
125
- value=api_key,
126
- type="password"
127
- )
128
-
129
- chatbot = gr.Chatbot(height=400)
130
- with gr.Row():
131
- message = gr.Textbox(
132
- label="Type your message here...",
133
- placeholder="Enter your message and press enter",
134
- lines=2
135
  )
136
- with gr.Row():
137
- submit = gr.Button("Submit")
138
- clear = gr.Button("Clear Chat")
139
-
140
- # 状态显示
141
- status = gr.Textbox(label="Status", interactive=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
142
 
143
- def update_api_key(new_key):
144
  nonlocal fastgpt_chat
145
- fastgpt_chat = FastGPTChat(new_key)
146
- return "API Key updated"
147
 
148
  # 设置事件处理
149
  submit_event = submit.click(
150
  fastgpt_chat.chat,
151
  inputs=[message, chatbot],
152
- outputs=[message, chatbot]
 
153
  )
154
 
155
  message.submit(
@@ -159,7 +175,19 @@ def create_chat_interface(api_key):
159
  )
160
 
161
  clear.click(lambda: None, None, chatbot, queue=False)
162
- api_key_input.change(update_api_key, inputs=[api_key_input], outputs=[status])
 
 
 
 
 
 
 
 
 
 
 
 
163
 
164
  return interface
165
 
 
9
  logger = logging.getLogger(__name__)
10
 
11
  class FastGPTChat:
12
+ def __init__(self, api_key, system_prompt="", base_url="https://api.fastgpt.in/api"):
13
  self.api_key = api_key
14
  self.base_url = base_url
15
+ self.system_prompt = system_prompt
16
  self.headers = {
17
  "Authorization": f"Bearer {api_key}",
18
  "Content-Type": "application/json"
 
24
 
25
  chat_id = str(uuid.uuid4())
26
 
27
+ # 构建消息历史,包含系统提示词
28
+ messages = []
29
+ if self.system_prompt:
30
+ messages.append({
31
+ "role": "system",
32
+ "content": self.system_prompt
33
+ })
34
+
35
+ # 添加聊天历史
36
+ for user_msg, bot_msg in chat_history:
37
+ messages.append({"role": "user", "content": user_msg})
38
+ messages.append({"role": "assistant", "content": bot_msg})
39
+
40
+ # 添加当前用户消息
41
+ messages.append({"role": "user", "content": message})
42
+
43
  # 准备请求数据
44
  data = {
45
  "chatId": chat_id,
46
+ "stream": True, # 启用流式响应
47
  "detail": True,
48
+ "model": "gpt-4o",
49
+ "messages": messages
 
 
 
 
 
50
  }
51
 
52
  try:
53
+ # 发送流式请求
 
 
 
 
 
54
  response = requests.post(
55
  f"{self.base_url}/v1/chat/completions",
56
  headers=self.headers,
57
  json=data,
58
+ stream=True,
59
  timeout=30
60
  )
61
 
 
 
 
 
 
 
62
  if response.status_code != 200:
63
+ error_msg = f"API Error: Status {response.status_code}"
64
  logger.error(error_msg)
65
  chat_history.append((message, f"Error: {error_msg}"))
66
  return "", chat_history
67
 
68
+ # 处理流式响应
69
+ full_response = ""
70
+ for line in response.iter_lines():
71
+ if line:
72
+ try:
73
+ line = line.decode('utf-8')
74
+ if line.startswith('data: '):
75
+ data = json.loads(line[6:])
76
+ if 'choices' in data and len(data['choices']) > 0:
77
+ content = data['choices'][0]['delta'].get('content', '')
78
+ if content:
79
+ full_response += content
80
+ # 更新聊天历史
81
+ if len(chat_history) > 0 and chat_history[-1][0] == message:
82
+ chat_history[-1] = (message, full_response)
83
+ else:
84
+ chat_history.append((message, full_response))
85
+ yield "", chat_history
86
+ except Exception as e:
87
+ logger.error(f"Error processing stream: {str(e)}")
88
+
89
+ return "", chat_history
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
 
91
  except requests.exceptions.RequestException as e:
92
  error_msg = f"Request failed: {str(e)}"
 
98
  # 创建FastGPT聊天实例
99
  fastgpt_chat = FastGPTChat(api_key)
100
 
101
+ # 创建美化后的Gradio界面
102
+ with gr.Blocks(
103
+ title="FastGPT Chat",
104
+ css="""
105
+ .container { max-width: 800px; margin: auto; }
106
+ .chat-header { text-align: center; padding: 20px; }
107
+ .chat-container { background-color: #f5f5f5; border-radius: 10px; padding: 20px; }
108
+ """
109
+ ) as interface:
110
+ with gr.Column(elem_classes="container"):
111
+ gr.Markdown(
112
+ """
113
+ # 🤖 FastGPT Chat Interface
114
+ ### Powered by GPT-4o
115
+ """
 
 
116
  )
117
+
118
+ with gr.Row():
119
+ api_key_input = gr.Textbox(
120
+ label="API Key",
121
+ value=api_key,
122
+ type="password",
123
+ container=False,
124
+ scale=4
125
+ )
126
+
127
+ with gr.Row():
128
+ system_prompt = gr.Textbox(
129
+ label="System Prompt",
130
+ placeholder="Set the behavior of AI assistant...",
131
+ lines=2,
132
+ container=False
133
+ )
134
+
135
+ with gr.Column(elem_classes="chat-container"):
136
+ chatbot = gr.Chatbot(
137
+ height=500,
138
+ container=False,
139
+ elem_classes="chatbot"
140
+ )
141
+
142
+ with gr.Row():
143
+ message = gr.Textbox(
144
+ label="Message",
145
+ placeholder="Type your message here...",
146
+ lines=2,
147
+ container=False,
148
+ scale=4
149
+ )
150
+
151
+ with gr.Row():
152
+ submit = gr.Button("Send 📤", variant="primary")
153
+ clear = gr.Button("Clear 🗑️", variant="secondary")
154
+
155
+ # 状态显示
156
+ status = gr.Textbox(label="Status", interactive=False)
157
 
158
+ def update_chat_settings(new_key, new_prompt):
159
  nonlocal fastgpt_chat
160
+ fastgpt_chat = FastGPTChat(new_key, new_prompt)
161
+ return "Settings updated"
162
 
163
  # 设置事件处理
164
  submit_event = submit.click(
165
  fastgpt_chat.chat,
166
  inputs=[message, chatbot],
167
+ outputs=[message, chatbot],
168
+ api_name="chat"
169
  )
170
 
171
  message.submit(
 
175
  )
176
 
177
  clear.click(lambda: None, None, chatbot, queue=False)
178
+
179
+ # 更新设置
180
+ api_key_input.change(
181
+ update_chat_settings,
182
+ inputs=[api_key_input, system_prompt],
183
+ outputs=[status]
184
+ )
185
+
186
+ system_prompt.change(
187
+ update_chat_settings,
188
+ inputs=[api_key_input, system_prompt],
189
+ outputs=[status]
190
+ )
191
 
192
  return interface
193