TeddyYao commited on
Commit
bf9764d
·
verified ·
1 Parent(s): df53ece

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +121 -43
app.py CHANGED
@@ -1,13 +1,13 @@
1
  import streamlit as st
2
- import openai
3
  import logging
4
- import os
 
5
  from typing import Optional
6
 
7
  # 配置日志
8
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
9
 
10
- def generate_email(
11
  profile1: str,
12
  profile2: str,
13
  style: str = "friendly",
@@ -15,14 +15,14 @@ def generate_email(
15
  api_key: Optional[str] = None
16
  ) -> str:
17
  """
18
- 基于两个LinkedIn简介生成个性化咖啡聊天邀请邮件。
19
 
20
  参数:
21
  profile1 (str): 发件人的LinkedIn简介文本
22
  profile2 (str): 收件人的LinkedIn简介文本
23
  style (str): 邮件风格,可选项为 "formal", "friendly", "humorous"
24
  temperature (float): 生成文本的创造性程度 (0.0-1.0)
25
- api_key (str, optional): OpenAI API密钥,如果未提供则使用环境变量
26
 
27
  返回:
28
  str: 生成的个性化咖啡聊天邮件
@@ -41,9 +41,9 @@ def generate_email(
41
  logging.warning(f"温度 {temperature} 超出范围,调整至 0.7")
42
  temperature = 0.7
43
 
44
- # 设置API密钥
45
- if api_key:
46
- openai.api_key = api_key
47
 
48
  # 构建提示词
49
  prompt = f"""
@@ -80,27 +80,57 @@ def generate_email(
80
  Format the response as a complete, ready-to-send email without explanations.
81
  """
82
 
83
- # 调用OpenAI API
84
- response = openai.chat.completions.create(
85
- model="gpt-4",
86
- messages=[
87
- {"role": "system", "content": "You are an expert email writer who helps professionals create personalized networking messages."},
 
 
 
 
 
 
 
 
 
 
 
88
  {"role": "user", "content": prompt}
89
  ],
90
- temperature=temperature,
91
- max_tokens=1000
92
- )
 
 
 
93
 
94
- # 提取并返回生成的邮件
95
- email_text = response.choices[0].message.content.strip()
96
- return email_text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97
 
98
  except ValueError as e:
99
  logging.error(f"输入错误: {str(e)}")
100
  return f"发生错误: {str(e)}"
101
- except openai.OpenAIError as e:
102
- logging.error(f"OpenAI API错误: {str(e)}")
103
- return f"OpenAI API错误: {str(e)}"
104
  except Exception as e:
105
  logging.error(f"意外错误: {str(e)}")
106
  return f"发生未预期的错误: {str(e)}"
@@ -117,19 +147,50 @@ st.title("☕ 个性化咖啡聊天邮件生成器")
117
  st.markdown("""
118
  此应用可以帮助求职者生成个性化的咖啡聊天邀请邮件。
119
  只需输入您的简介和目标联系人的简介,系统将分析共同点并生成一封真诚的邀请邮件。
 
 
120
  """)
121
 
122
- # 侧边栏 - API密钥设置
123
  with st.sidebar:
124
- st.header("设置")
125
- api_key = st.text_input("OpenAI API密钥", type="password", key="api_key")
126
- if api_key:
127
- os.environ["OPENAI_API_KEY"] = api_key
128
- else:
129
- # 尝试从环境变量获取
130
- api_key = os.environ.get("OPENAI_API_KEY")
131
  if not api_key:
132
- st.warning("请输入OpenAI API密钥以使用此应用")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
133
 
134
  st.subheader("邮件风格")
135
  style = st.radio(
@@ -169,14 +230,14 @@ with col2:
169
  submit_disabled = not api_key or not profile1 or not profile2
170
  if submit_disabled:
171
  if not api_key:
172
- reason = "请先输入OpenAI API密钥"
173
  else:
174
  reason = "请填写两个简介"
175
  st.warning(reason)
176
 
177
  if st.button("生成邮件", type="primary", disabled=submit_disabled):
178
  with st.spinner("正在分析简介并创建个性化邮件..."):
179
- email = generate_email(
180
  profile1=profile1,
181
  profile2=profile2,
182
  style=style,
@@ -184,17 +245,33 @@ if st.button("生成邮件", type="primary", disabled=submit_disabled):
184
  api_key=api_key
185
  )
186
 
187
- st.success("邮件已生成!")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
188
 
189
- # 显示结果
190
- st.header("您的个性化咖啡聊天邮件")
191
- st.text_area("可复制的邮件内容", email, height=400)
192
- st.download_button(
193
- label="下载邮件",
194
- data=email,
195
- file_name="咖啡聊天邀请.txt",
196
- mime="text/plain"
197
- )
198
 
199
  # 使用提示
200
  st.markdown("---")
@@ -204,4 +281,5 @@ st.markdown("""
204
  - **尝试不同风格**以适应不同的行业和联系人
205
  - 生成后可以**微调邮件内容**,添加您认为合适的个人细节
206
  - 适合用于**金融、咨询和科技行业**的专业人士
 
207
  """)
 
1
  import streamlit as st
 
2
  import logging
3
+ import requests
4
+ import json
5
  from typing import Optional
6
 
7
  # 配置日志
8
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
9
 
10
+ def generate_email_with_vveai(
11
  profile1: str,
12
  profile2: str,
13
  style: str = "friendly",
 
15
  api_key: Optional[str] = None
16
  ) -> str:
17
  """
18
+ 使用VVEAI API基于两个LinkedIn简介生成个性化咖啡聊天邀请邮件。
19
 
20
  参数:
21
  profile1 (str): 发件人的LinkedIn简介文本
22
  profile2 (str): 收件人的LinkedIn简介文本
23
  style (str): 邮件风格,可选项为 "formal", "friendly", "humorous"
24
  temperature (float): 生成文本的创造性程度 (0.0-1.0)
25
+ api_key (str, optional): VVEAI API密钥
26
 
27
  返回:
28
  str: 生成的个性化咖啡聊天邮件
 
41
  logging.warning(f"温度 {temperature} 超出范围,调整至 0.7")
42
  temperature = 0.7
43
 
44
+ # 验证API密钥
45
+ if not api_key:
46
+ raise ValueError("请提供VVEAI API密钥")
47
 
48
  # 构建提示词
49
  prompt = f"""
 
80
  Format the response as a complete, ready-to-send email without explanations.
81
  """
82
 
83
+ # 准备API请求
84
+ system_message = "You are an expert email writer who helps professionals create personalized networking messages."
85
+
86
+ # VVEAI API端点
87
+ url = "https://api.vveai.com/v1/chat/completions"
88
+
89
+ # 构建请求
90
+ headers = {
91
+ "Content-Type": "application/json",
92
+ "Authorization": f"Bearer {api_key}"
93
+ }
94
+
95
+ payload = {
96
+ "model": "gpt-4", # 可能需要根据VVEAI支持的模型调整
97
+ "messages": [
98
+ {"role": "system", "content": system_message},
99
  {"role": "user", "content": prompt}
100
  ],
101
+ "temperature": temperature,
102
+ "max_tokens": 1000
103
+ }
104
+
105
+ # 发送请求
106
+ response = requests.post(url, headers=headers, data=json.dumps(payload), timeout=60)
107
 
108
+ # 添加详细日志便于调试
109
+ logging.info(f"API响应状态码: {response.status_code}")
110
+ logging.info(f"API响应头: {response.headers}")
111
+
112
+ # 处理响应
113
+ if response.status_code == 200:
114
+ result = response.json()
115
+ # 记录完整响应便于调试
116
+ logging.info(f"API响应内容: {result}")
117
+ try:
118
+ email_text = result["choices"][0]["message"]["content"].strip()
119
+ return email_text
120
+ except KeyError as e:
121
+ logging.error(f"响应格式错误: {e}. 完整响应: {result}")
122
+ return f"API响应格式错误: {e}。请联系VVEAI支持获取帮助。"
123
+ else:
124
+ error_message = f"API请求失败: {response.status_code} - {response.text}"
125
+ logging.error(error_message)
126
+ return f"API错误: {response.status_code}。请检查您的API密钥是否正确。详细信息: {response.text}"
127
 
128
  except ValueError as e:
129
  logging.error(f"输入错误: {str(e)}")
130
  return f"发生错误: {str(e)}"
131
+ except requests.RequestException as e:
132
+ logging.error(f"请求错误: {str(e)}")
133
+ return f"网络请求错误: {str(e)}"
134
  except Exception as e:
135
  logging.error(f"意外错误: {str(e)}")
136
  return f"发生未预期的错误: {str(e)}"
 
147
  st.markdown("""
148
  此应用可以帮助求职者生成个性化的咖啡聊天邀请邮件。
149
  只需输入您的简介和目标联系人的简介,系统将分析共同点并生成一封真诚的邀请邮件。
150
+
151
+ **注意:此应用使用 VVEAI API 服务,请确保输入正确的 API 密钥。**
152
  """)
153
 
154
+ # 侧边栏 - API设置
155
  with st.sidebar:
156
+ st.header("API设置")
157
+
158
+ api_key = st.text_input("VVEAI API密钥", type="password", key="api_key",
159
+ help="输入以 sk- 开头的 VVEAI API 密钥")
160
+
161
+ # 添加API状态检测按钮
162
+ if st.button("测试API连接"):
163
  if not api_key:
164
+ st.error("请先输入API密钥")
165
+ else:
166
+ try:
167
+ # 简单的API测试请求
168
+ test_url = "https://api.vveai.com/v1/chat/completions"
169
+ test_headers = {
170
+ "Content-Type": "application/json",
171
+ "Authorization": f"Bearer {api_key}"
172
+ }
173
+ test_payload = {
174
+ "model": "gpt-4",
175
+ "messages": [
176
+ {"role": "user", "content": "Hello"}
177
+ ],
178
+ "max_tokens": 5
179
+ }
180
+
181
+ test_response = requests.post(
182
+ test_url,
183
+ headers=test_headers,
184
+ data=json.dumps(test_payload),
185
+ timeout=10
186
+ )
187
+
188
+ if test_response.status_code == 200:
189
+ st.success("API连接成功!")
190
+ else:
191
+ st.error(f"API连接失败: {test_response.status_code} - {test_response.text}")
192
+ except Exception as e:
193
+ st.error(f"测试API时出错: {str(e)}")
194
 
195
  st.subheader("邮件风格")
196
  style = st.radio(
 
230
  submit_disabled = not api_key or not profile1 or not profile2
231
  if submit_disabled:
232
  if not api_key:
233
+ reason = "请先输入VVEAI API密钥"
234
  else:
235
  reason = "请填写两个简介"
236
  st.warning(reason)
237
 
238
  if st.button("生成邮件", type="primary", disabled=submit_disabled):
239
  with st.spinner("正在分析简介并创建个性化邮件..."):
240
+ email = generate_email_with_vveai(
241
  profile1=profile1,
242
  profile2=profile2,
243
  style=style,
 
245
  api_key=api_key
246
  )
247
 
248
+ # 检查是否发生错误
249
+ if email.startswith("发生错误") or email.startswith("API错误") or email.startswith("网络请求错误"):
250
+ st.error(email)
251
+ else:
252
+ st.success("邮件已生成!")
253
+
254
+ # 显示结果
255
+ st.header("您的个性化咖啡聊天邮件")
256
+ st.text_area("可复制的邮件内容", email, height=400)
257
+ st.download_button(
258
+ label="下载邮件",
259
+ data=email,
260
+ file_name="咖啡聊天邀请.txt",
261
+ mime="text/plain"
262
+ )
263
+
264
+ # 调试信息(可选,帮助解决API问题)
265
+ if st.checkbox("显示调试信息"):
266
+ st.subheader("API信息")
267
+ st.markdown("""
268
+ - API端点: `https://api.vveai.com/v1/chat/completions`
269
+ - 请求方法: POST
270
+ - 内容类型: application/json
271
+ - 授权方式: Bearer Token
272
 
273
+ 如果遇到持续的API问题,请联系VVEAI支持团队并提供以上信息。
274
+ """)
 
 
 
 
 
 
 
275
 
276
  # 使用提示
277
  st.markdown("---")
 
281
  - **尝试不同风格**以适应不同的行业和联系人
282
  - 生成后可以**微调邮件内容**,添加您认为合适的个人细节
283
  - 适合用于**金融、咨询和科技行业**的专业人士
284
+ - 如果API连接测试失败,请确认您的**VVEAI API密钥**是否正确
285
  """)