ValueFX9507 commited on
Commit
9322929
·
verified ·
1 Parent(s): 92a5319

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +29 -13
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
- response = openai.ChatCompletion.create(
54
- model="mini",
55
- messages=messages,
56
- stream=True
57
- )
 
 
 
 
 
 
58
 
59
  collected_messages = []
60
- for chunk in response:
61
- if chunk and hasattr(chunk.choices[0].delta, "content"):
62
- chunk_message = chunk.choices[0].delta.content
63
- collected_messages.append(chunk_message)
64
- partial_message = "".join(collected_messages)
65
- formatted_message = format_think_tags(partial_message)
66
- yield formatted_message
 
 
 
 
 
 
 
 
 
 
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(share=False, server_name="0.0.0.0", server_port=7860)
 
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()