mistpe commited on
Commit
ba1e087
·
verified ·
1 Parent(s): e4748a7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +106 -106
app.py CHANGED
@@ -1,106 +1,106 @@
1
- from flask import Flask, render_template, request, Response
2
- from openai import OpenAI
3
- from dotenv import load_dotenv
4
- import os
5
- import json
6
- from datetime import datetime
7
-
8
- load_dotenv()
9
-
10
- app = Flask(__name__)
11
- client = OpenAI(
12
- api_key=os.getenv('OPENAI_API_KEY'),
13
- base_url=os.getenv('OPENAI_BASE_URL')
14
- )
15
-
16
- class ChatBot:
17
- def __init__(self):
18
- self.messages = []
19
- # 加载系统提示词
20
- self.system_prompt = self.load_system_prompt()
21
-
22
- def load_system_prompt(self):
23
- # 从文件加载系统提示词
24
- try:
25
- with open('system_prompt.txt', 'r', encoding='utf-8') as file:
26
- return file.read()
27
- except Exception as e:
28
- print(f"Error loading system prompt: {e}")
29
- return ""
30
-
31
- def format_birth_info(self, birth_info):
32
- """格式化出生信息用于分析"""
33
- try:
34
- birth_date = datetime.strptime(birth_info['date'], '%Y年%m月%d日')
35
- formatted_date = birth_date.strftime('%Y年%m月%d日')
36
- return f"{formatted_date} {birth_info['time']}"
37
- except Exception as e:
38
- print(f"Error formatting birth info: {e}")
39
- return birth_info['raw']
40
-
41
- def prepare_analysis_prompt(self, user_data):
42
- """准备用于分析的完整提示词"""
43
- birth_info = self.format_birth_info(user_data['birth_info'])
44
-
45
- analysis_prompt = f"""根据以下信息进行命理分析:
46
- 出生信息:{birth_info}
47
- 咨询问题:{user_data['question']}
48
-
49
- 请基于此信息,结合八字、紫微斗数等进行分析。"""
50
-
51
- return analysis_prompt
52
-
53
- def get_stream_response(self, user_input):
54
- """处理用户输入并生成流式响应"""
55
- try:
56
- # 解析用户输入的JSON数据
57
- user_data = json.loads(user_input)
58
-
59
- # 如果是新的对话,添加系统提示词
60
- if not self.messages:
61
- self.messages.append({"role": "system", "content": self.system_prompt})
62
-
63
- # 准备分析提示词
64
- analysis_prompt = self.prepare_analysis_prompt(user_data)
65
- self.messages.append({"role": "user", "content": analysis_prompt})
66
-
67
- # 创建流式响应
68
- response = client.chat.completions.create(
69
- model=os.getenv('OPENAI_MODEL'),
70
- messages=self.messages,
71
- stream=True,
72
- temperature=0.7,
73
- max_tokens=2000
74
- )
75
-
76
- for chunk in response:
77
- if chunk.choices[0].delta.content:
78
- yield f"data: {json.dumps({'content': chunk.choices[0].delta.content})}\n\n"
79
-
80
- # 保存完整对话到历史记录
81
- full_response = ''.join(chunk.choices[0].delta.content or ''
82
- for chunk in response)
83
- self.messages.append({"role": "assistant", "content": full_response})
84
-
85
- except Exception as e:
86
- yield f"data: {json.dumps({'error': str(e)})}\n\n"
87
-
88
- chatbot = ChatBot()
89
-
90
- @app.route('/')
91
- def home():
92
- return render_template('index.html')
93
-
94
- @app.route('/chat', methods=['POST'])
95
- def chat():
96
- try:
97
- user_message = request.get_json()
98
- return Response(
99
- chatbot.get_stream_response(json.dumps(user_message)),
100
- mimetype='text/event-stream'
101
- )
102
- except Exception as e:
103
- return jsonify({'error': str(e)}), 500
104
-
105
- if __name__ == '__main__':
106
- app.run(debug=True)
 
1
+ from flask import Flask, render_template, request, Response
2
+ from openai import OpenAI
3
+ from dotenv import load_dotenv
4
+ import os
5
+ import json
6
+ from datetime import datetime
7
+
8
+ load_dotenv()
9
+
10
+ app = Flask(__name__)
11
+ client = OpenAI(
12
+ api_key=os.getenv('OPENAI_API_KEY'),
13
+ base_url=os.getenv('OPENAI_BASE_URL')
14
+ )
15
+
16
+ class ChatBot:
17
+ def __init__(self):
18
+ self.messages = []
19
+ # 加载系统提示词
20
+ self.system_prompt = self.load_system_prompt()
21
+
22
+ def load_system_prompt(self):
23
+ # 从文件加载系统提示词
24
+ try:
25
+ with open('system_prompt.txt', 'r', encoding='utf-8') as file:
26
+ return file.read()
27
+ except Exception as e:
28
+ print(f"Error loading system prompt: {e}")
29
+ return ""
30
+
31
+ def format_birth_info(self, birth_info):
32
+ """格式化出生信息用于分析"""
33
+ try:
34
+ birth_date = datetime.strptime(birth_info['date'], '%Y年%m月%d日')
35
+ formatted_date = birth_date.strftime('%Y年%m月%d日')
36
+ return f"{formatted_date} {birth_info['time']}"
37
+ except Exception as e:
38
+ print(f"Error formatting birth info: {e}")
39
+ return birth_info['raw']
40
+
41
+ def prepare_analysis_prompt(self, user_data):
42
+ """准备用于分析的完整提示词"""
43
+ birth_info = self.format_birth_info(user_data['birth_info'])
44
+
45
+ analysis_prompt = f"""根据以下信息进行命理分析:
46
+ 出生信息:{birth_info}
47
+ 咨询问题:{user_data['question']}
48
+
49
+ 请基于此信息,结合八字、紫微斗数等进行分析。"""
50
+
51
+ return analysis_prompt
52
+
53
+ def get_stream_response(self, user_input):
54
+ """处理用户输入并生成流式响应"""
55
+ try:
56
+ # 解析用户输入的JSON数据
57
+ user_data = json.loads(user_input)
58
+
59
+ # 如果是新的对话,添加系统提示词
60
+ if not self.messages:
61
+ self.messages.append({"role": "system", "content": self.system_prompt})
62
+
63
+ # 准备分析提示词
64
+ analysis_prompt = self.prepare_analysis_prompt(user_data)
65
+ self.messages.append({"role": "user", "content": analysis_prompt})
66
+
67
+ # 创建流式响应
68
+ response = client.chat.completions.create(
69
+ model=os.getenv('OPENAI_MODEL'),
70
+ messages=self.messages,
71
+ stream=True,
72
+ temperature=0.7,
73
+ max_tokens=2000
74
+ )
75
+
76
+ for chunk in response:
77
+ if chunk.choices[0].delta.content:
78
+ yield f"data: {json.dumps({'content': chunk.choices[0].delta.content})}\n\n"
79
+
80
+ # 保存完整对话到历史记录
81
+ full_response = ''.join(chunk.choices[0].delta.content or ''
82
+ for chunk in response)
83
+ self.messages.append({"role": "assistant", "content": full_response})
84
+
85
+ except Exception as e:
86
+ yield f"data: {json.dumps({'error': str(e)})}\n\n"
87
+
88
+ chatbot = ChatBot()
89
+
90
+ @app.route('/')
91
+ def home():
92
+ return render_template('index.html')
93
+
94
+ @app.route('/chat', methods=['POST'])
95
+ def chat():
96
+ try:
97
+ user_message = request.get_json()
98
+ return Response(
99
+ chatbot.get_stream_response(json.dumps(user_message)),
100
+ mimetype='text/event-stream'
101
+ )
102
+ except Exception as e:
103
+ return jsonify({'error': str(e)}), 500
104
+
105
+ if __name__ == '__main__':
106
+ app.run(host='0.0.0.0', port=7860, debug=False)