leonsimon23 commited on
Commit
1590d77
·
verified ·
1 Parent(s): d2d3136

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +75 -108
app.py CHANGED
@@ -1,112 +1,79 @@
1
  import gradio as gr
2
  import requests
3
- import time
4
  import json
5
-
6
-
7
- # 设置 FastGPT API 的基本信息
8
- #API_URL = "https://api.fastgpt.in/api/v1/chat/completions" # 请根据您的部署地址修改
9
- #API_KEY = "fastgpt-aleL83PzPiul9lZDJQFD4NHYfVIxP7mDIWFCyin2FuMhYgwlRC3NMkV2K5lxc8gF" # 请替换为您的实际 API 密钥
10
-
11
-
12
- # 设置 FastGPT API 的基本信息
13
- #API_URL = "https://api.fastgpt.com/generate" # 请根据您的实际部署地址修改
14
- #API_KEY = "fastgpt-aleL83PzPiul9lZDJQFD4NHYfVIxP7mDIWFCyin2FuMhYgwlRC3NMkV2K5lxc8gF" # 请替换为您的实际 API 密钥
15
-
16
- #import gradio as gr
17
- #import requests
18
-
19
- #API_KEY = "fastgpt-aleL83PzPiul9lZDJQFD4NHYfVIxP7mDIWFCyin2FuMhYgwlRC3NMkV2K5lxc8gF" # 请替换为您的实际 API 密钥
20
-
21
- #API_URL = "https://api.fastgpt.com/v1/chat"
22
-
23
-
24
- # 替换成你的 FastGPT 的 BaseURL 和 应用特定 API Key
25
- #BASE_URL = "https://api.fastgpt.in/api/v1"
26
- #API_KEY = "fastgpt-aleL83PzPiul9lZDJQFD4NHYfVIxP7mDIWFCyin2FuMhYgwlRC3NMkV2K5lxc8gF" # 应用特定 key
27
-
28
- # 替换成你的 FastGPT 的 BaseURL 和 应用特定 API Key
29
- BASE_URL = "https://api.fastgpt.in/api/v1"
30
- API_KEY = "fastgpt-aleL83PzPiul9lZDJQFD4NHYfVIxP7mDIWFCyin2FuMhYgwlRC3NMkV2K5lxc8gF" # 应用特定 key
31
-
32
-
33
- import ijson # Install with: pip install ijson
34
-
35
-
36
- def chat_with_fastgpt(message, history):
37
- """
38
- 与 FastGPT 进行对话的函数
39
-
40
- Args:
41
- message: 用户输入的消息
42
- history: 聊天历史记录
43
-
44
- Returns:
45
- 生成器的响应内容
46
- """
47
- headers = {
48
- "Authorization": f"Bearer {API_KEY}",
49
- "Content-Type": "application/json",
50
- }
51
-
52
- # 构建消息历史
53
- messages = []
54
- for human, assistant in history:
55
- messages.append({"role": "user", "content": human})
56
- messages.append({"role": "assistant", "content": assistant})
57
- messages.append({"role": "user", "content": message})
58
-
59
- data = {
60
- "chatId": "your_chat_id", # 如果需要,替换成你的 chatId
61
- "stream": True, # 仍然使用流式请求
62
- "detail": False,
63
- "messages": messages,
64
- }
65
-
66
- try:
67
- response = requests.post(
68
- f"{BASE_URL}/chat/completions", headers=headers, json=data, stream=True
 
69
  )
70
- response.raise_for_status()
71
-
72
- buffer = ""
73
- for chunk in response.iter_content(chunk_size=8192):
74
- if chunk:
75
- buffer += chunk.decode('utf-8')
76
-
77
- # 尝试解析 JSON 对象
78
- while True: # Continue processing the buffer until no more complete objects are found
79
- try:
80
- first_brace_index = buffer.find('{')
81
- if first_brace_index == -1:
82
- break
83
-
84
- obj, end_index = json.JSONDecoder().raw_decode(buffer[first_brace_index:])
85
-
86
- # 解析成功,处理 JSON 对象
87
- if obj.get("choices"):
88
- delta = obj["choices"][0].get("delta")
89
- if delta and delta.get("content"):
90
- yield delta["content"]
91
-
92
- buffer = buffer[first_brace_index + end_index:]
93
-
94
- except json.JSONDecodeError as e:
95
- break
96
-
97
- except requests.exceptions.RequestException as e:
98
- print(f"请求错误: {e}")
99
- yield "请求 FastGPT API 出错,请检查网络或 API Key。"
100
- except Exception as e:
101
- print(f"未知错误: {e}")
102
- print(f"错误信息: {e}")
103
- yield "发生未知错误。"
104
-
105
- # Gradio 界面
106
- iface = gr.ChatInterface(
107
- fn=chat_with_fastgpt,
108
- title="FastGPT Chatbot",
109
- description="与 FastGPT 支持的聊天机器人对话",
110
- )
111
-
112
- iface.launch()
 
1
  import gradio as gr
2
  import requests
 
3
  import json
4
+ import uuid
5
+
6
+ class FastGPTChat:
7
+ def __init__(self, api_key, base_url="https://api.fastgpt.in/api"):
8
+ self.api_key = api_key
9
+ self.base_url = base_url
10
+ self.headers = {
11
+ "Authorization": f"Bearer {api_key}",
12
+ "Content-Type": "application/json"
13
+ }
14
+
15
+ def chat(self, message, chat_history):
16
+ # 生成唯一的聊天ID
17
+ chat_id = str(uuid.uuid4())
18
+
19
+ # 准备请求数据
20
+ data = {
21
+ "chatId": chat_id,
22
+ "stream": False,
23
+ "detail": False,
24
+ "messages": [
25
+ {
26
+ "role": "user",
27
+ "content": message
28
+ }
29
+ ]
30
+ }
31
+
32
+ try:
33
+ # 发送请求
34
+ response = requests.post(
35
+ f"{self.base_url}/v1/chat/completions",
36
+ headers=self.headers,
37
+ json=data
38
+ )
39
+ response.raise_for_status()
40
+
41
+ # 解析响应
42
+ response_data = response.json()
43
+ ai_message = response_data["choices"][0]["message"]["content"]
44
+
45
+ # 更新对话历史
46
+ chat_history.append((message, ai_message))
47
+ return "", chat_history
48
+
49
+ except Exception as e:
50
+ return f"Error: {str(e)}", chat_history
51
+
52
+ def create_chat_interface(api_key):
53
+ # 创建FastGPT聊天实例
54
+ fastgpt_chat = FastGPTChat(api_key)
55
+
56
+ # 创建Gradio界面
57
+ with gr.Blocks(title="FastGPT Chat") as interface:
58
+ gr.Markdown("# FastGPT Chat Interface")
59
+
60
+ chatbot = gr.Chatbot(height=400)
61
+ message = gr.Textbox(label="Type your message here...", placeholder="Enter your message and press enter")
62
+ clear = gr.Button("Clear Chat")
63
+
64
+ # 设置事件处理
65
+ message.submit(
66
+ fastgpt_chat.chat,
67
+ inputs=[message, chatbot],
68
+ outputs=[message, chatbot]
69
  )
70
+
71
+ clear.click(lambda: None, None, chatbot, queue=False)
72
+
73
+ return interface
74
+
75
+ # 使用示例
76
+ if __name__ == "__main__":
77
+ API_KEY = "your-fastgpt-api-key-here" # 替换为你的API密钥
78
+ demo = create_chat_interface(API_KEY)
79
+ demo.launch()