Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -30,6 +30,10 @@ BASE_URL = "https://api.fastgpt.in/api/v1"
|
|
30 |
API_KEY = "fastgpt-aleL83PzPiul9lZDJQFD4NHYfVIxP7mDIWFCyin2FuMhYgwlRC3NMkV2K5lxc8gF" # 应用特定 key
|
31 |
|
32 |
|
|
|
|
|
|
|
|
|
33 |
def chat_with_fastgpt(message, history):
|
34 |
"""
|
35 |
与 FastGPT 进行对话的函数
|
@@ -59,29 +63,29 @@ def chat_with_fastgpt(message, history):
|
|
59 |
"detail": False,
|
60 |
"messages": messages,
|
61 |
}
|
62 |
-
|
63 |
try:
|
64 |
response = requests.post(
|
65 |
f"{BASE_URL}/chat/completions", headers=headers, json=data, stream=True
|
66 |
)
|
67 |
-
response.raise_for_status()
|
68 |
-
|
69 |
-
#
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
|
86 |
except requests.exceptions.RequestException as e:
|
87 |
print(f"请求错误: {e}")
|
@@ -89,6 +93,7 @@ def chat_with_fastgpt(message, history):
|
|
89 |
except Exception as e:
|
90 |
print(f"未知错误: {e}")
|
91 |
yield "发生未知错误。"
|
|
|
92 |
# Gradio 界面
|
93 |
iface = gr.ChatInterface(
|
94 |
fn=chat_with_fastgpt,
|
|
|
30 |
API_KEY = "fastgpt-aleL83PzPiul9lZDJQFD4NHYfVIxP7mDIWFCyin2FuMhYgwlRC3NMkV2K5lxc8gF" # 应用特定 key
|
31 |
|
32 |
|
33 |
+
import ijson # Install with: pip install ijson
|
34 |
+
|
35 |
+
|
36 |
+
|
37 |
def chat_with_fastgpt(message, history):
|
38 |
"""
|
39 |
与 FastGPT 进行对话的函数
|
|
|
63 |
"detail": False,
|
64 |
"messages": messages,
|
65 |
}
|
66 |
+
|
67 |
try:
|
68 |
response = requests.post(
|
69 |
f"{BASE_URL}/chat/completions", headers=headers, json=data, stream=True
|
70 |
)
|
71 |
+
response.raise_for_status()
|
72 |
+
|
73 |
+
# Use ijson to parse the stream
|
74 |
+
parser = ijson.parse(response.raw) # Use response.raw for the raw byte stream
|
75 |
+
current_content = ""
|
76 |
+
for prefix, event, value in parser:
|
77 |
+
if prefix == "choices.item.message.content" and event == "string":
|
78 |
+
current_content += value
|
79 |
+
elif current_content:
|
80 |
+
# Yield the accumulated content
|
81 |
+
for i in range(0, len(current_content), 10):
|
82 |
+
yield current_content[i:i + 10]
|
83 |
+
current_content = ""
|
84 |
+
|
85 |
+
# Yield any remaining content
|
86 |
+
if current_content:
|
87 |
+
for i in range(0, len(current_content), 10):
|
88 |
+
yield current_content[i:i + 10]
|
89 |
|
90 |
except requests.exceptions.RequestException as e:
|
91 |
print(f"请求错误: {e}")
|
|
|
93 |
except Exception as e:
|
94 |
print(f"未知错误: {e}")
|
95 |
yield "发生未知错误。"
|
96 |
+
|
97 |
# Gradio 界面
|
98 |
iface = gr.ChatInterface(
|
99 |
fn=chat_with_fastgpt,
|