leonsimon23 commited on
Commit
177c1a2
·
verified ·
1 Parent(s): a313d63

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +24 -19
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
- # 1. Accumulate the entire response
70
- full_response = ""
71
- for chunk in response.iter_content(chunk_size=8192):
72
- if chunk:
73
- full_response += chunk.decode('utf-8')
74
-
75
- # Print the raw response for debugging
76
- print(f"------ Raw API Response ------\n{full_response}\n-----------------------------")
77
-
78
- # 2. Parse the response as a whole
79
- try:
80
- # ... (rest of the parsing and yielding logic)
81
-
82
- except json.JSONDecodeError:
83
- print(f"Failed to parse JSON: {full_response}")
84
- yield "Received invalid JSON data from the API."
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,