Spaces:
Sleeping
Sleeping
from openai import OpenAI | |
import os | |
import re | |
# 设置OpenAI API密钥和基础URL | |
api_key = os.getenv("OPENAI_API_KEY") | |
base_url = os.getenv("OPENAI_BASE_URL", "https://api.openai.com/v1") | |
model_name = os.getenv("OPENAI_MODEL_NAME", "gpt-3.5-turbo") | |
def analyze_style(profile, conversations): | |
client = OpenAI( | |
api_key=api_key, | |
base_url=base_url | |
) | |
# 提取患者信息 | |
patient_info = f"### 患者信息\n年龄:{profile['age']}\n性别:{profile['gender']}\n职业:{profile['occupation']}\n婚姻状况:{profile['marital_status']}\n症状:{profile['symptoms']}" | |
# 提取对话记录 | |
dialogue_history = "\n".join([f"{conv['role']}: {conv['content']}" for conv in conversations]) | |
# 构建提示词,明确要求模型按特定格式输出结果 | |
prompt = f"""### 任务 | |
根据患者情况及咨访对话历史记录分析患者的说话风格。 | |
{patient_info} | |
### 对话记录 | |
{dialogue_history} | |
请分析患者的说话风格,最多列出5种风格特点。 | |
请按以下格式输出结果: | |
说话风格: | |
1. [风格特点1] | |
2. [风格特点2] | |
3. [风格特点3] | |
... | |
只需要列出风格特点,不需要解释。 | |
""" | |
response = client.chat.completions.create( | |
model=model_name, | |
messages=[ | |
{"role": "user", "content": prompt} | |
] | |
) | |
# 从响应中提取说话风格列表 | |
response_text = response.choices[0].message.content | |
# 使用正则表达式提取风格特点 | |
# 匹配"说话风格:"之后的列表项 | |
style_pattern = r"说话风格:\s*(?:\d+\.\s*([^\n]+)(?:\n|$))+" | |
match = re.search(style_pattern, response_text, re.DOTALL) | |
if match: | |
# 提取所有的列表项 | |
style_items = re.findall(r"\d+\.\s*([^\n]+)", response_text) | |
return style_items | |
else: | |
# 如果没有按预期格式输出,尝试使用备用正则表达式 | |
# 寻找任何可能的列表项 | |
fallback_items = re.findall(r"(?:^|\n)(?:\d+[\.\)、]|[-•*])\s*([^\n]+)", response_text) | |
# 如果仍然没找到,尝试直接分割文本 | |
if not fallback_items: | |
# 找到可能包含风格描述的行 | |
potential_styles = [line.strip() for line in response_text.split('\n') | |
if line.strip() and not line.startswith('###') and ':' not in line] | |
return potential_styles[:5] # 最多返回5项 | |
return fallback_items[:5] # 最多返回5项 | |
# unit test | |
# profile = { | |
# "drisk": 3, | |
# "srisk": 2, | |
# "age": "42", | |
# "gender": "女", | |
# "marital_status": "离婚", | |
# "occupation": "教师", | |
# "symptoms": "缺乏自信心,自我价值感低,有自罪感,无望感;体重剧烈增加;精神运动性激越;有自杀想法" | |
# } | |
# conversations = [ | |
# {"role": "user", "content": "我最近感觉很沮丧,似乎一切都没有意义。"}, | |
# {"role": "assistant", "content": "你能具体说说是什么让你有这样的感觉吗?"}, | |
# {"role": "user", "content": "我觉得自己在工作上总是做不好,没什么价值。"} | |
# ] | |
# print(analyze_style(profile, conversations)) |