Update app.py
Browse files
app.py
CHANGED
@@ -50,20 +50,36 @@ def chat_stream(message: str, history: list, system_prompt: str) -> Iterator[str
|
|
50 |
messages.append({"role": "user", "content": message})
|
51 |
|
52 |
# 调用API进行流式对话
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
58 |
|
59 |
collected_messages = []
|
60 |
-
for
|
61 |
-
if
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
67 |
|
68 |
# 自定义CSS样式
|
69 |
custom_css = """
|
@@ -148,4 +164,4 @@ with gr.Blocks(css=custom_css) as demo:
|
|
148 |
# 启动应用
|
149 |
if __name__ == "__main__":
|
150 |
demo.queue()
|
151 |
-
demo.launch(
|
|
|
50 |
messages.append({"role": "user", "content": message})
|
51 |
|
52 |
# 调用API进行流式对话
|
53 |
+
headers = {
|
54 |
+
"Authorization": f"Bearer {API_KEY}",
|
55 |
+
"Content-Type": "application/json"
|
56 |
+
}
|
57 |
+
data = {
|
58 |
+
"model": "gpt-3.5-turbo",
|
59 |
+
"messages": messages,
|
60 |
+
"stream": True
|
61 |
+
}
|
62 |
+
|
63 |
+
response = requests.post(f"{API_BASE}/chat/completions", headers=headers, json=data, stream=True)
|
64 |
|
65 |
collected_messages = []
|
66 |
+
for line in response.iter_lines():
|
67 |
+
if line:
|
68 |
+
line = line.decode('utf-8')
|
69 |
+
if line.startswith("data: "):
|
70 |
+
json_str = line[6:]
|
71 |
+
if json_str.strip() == "[DONE]":
|
72 |
+
break
|
73 |
+
try:
|
74 |
+
chunk = json.loads(json_str)
|
75 |
+
if chunk['choices'][0]['delta'].get('content'):
|
76 |
+
chunk_message = chunk['choices'][0]['delta']['content']
|
77 |
+
collected_messages.append(chunk_message)
|
78 |
+
partial_message = "".join(collected_messages)
|
79 |
+
formatted_message = format_think_tags(partial_message)
|
80 |
+
yield formatted_message
|
81 |
+
except json.JSONDecodeError:
|
82 |
+
continue
|
83 |
|
84 |
# 自定义CSS样式
|
85 |
custom_css = """
|
|
|
164 |
# 启动应用
|
165 |
if __name__ == "__main__":
|
166 |
demo.queue()
|
167 |
+
demo.launch()
|