# -*- coding: gbk -*- import gradio as gr #from huggingface_hub import InferenceClient import os from pathlib import Path from openai import OpenAI import time class ChatgptAPI: def __init__(self, ): ''' self.client = OpenAI( api_key = os.environ.get("OPENAI_API_KEY"), base_url = "https://api.moonshot.cn/v1", ) ''' self.client=OpenAI( api_key=os.environ.get("TONGYI_API_KEY"), # 替换成真实DashScope的API_KEY base_url="https://dashscope.aliyuncs.com/compatible-mode/v1", # 填写DashScopebase_url ) def get_summary(self, file_path): file = self.client.files.create(file=Path(file_path), purpose="file-extract") completion = self.client.chat.completions.create( model="qwen-long", messages=[ { 'role': 'system', 'content': 'You are a helpful assistant.' }, { 'role': 'system', 'content': f'fileid://{file.id}' }, { 'role': 'user', 'content': '你是心理咨询督导专家,现在要对咨询师的咨询内容进行督导。不要依赖咨询师的回话,因为它可能是不正确的。step by step完成以下步骤:\n 步骤1-打开并阅读我上传的文本文件的全部内容,直到最后一个字符 \n 步骤2-在全文中摘取来访者的【关键性发言】,不要仅摘录文本前半部分的发言,最终选出其中最需要被讨论的3-4条,记录发言结束后第一个咨询师发起的回复内容为【咨询师的回复】 \n 步骤3-针对关键性发言,给出合适的【督导回话内容】 \n 步骤4-对比【督导回话内容】和【咨询师的回复】,并给每句回应打分(0分为与督导回话方案完全不一致,10分与督导回话方案完全一致) \n 步骤5-以上4步仅执行不输出,仅按以下json格式输出: [{"key_num" : "n", "visiter" : "来访者内容", "superior" : "督导回话方案内容", "adviser" : "咨询师的回复内容",:"score" : "x/10", "reason" : "修改原因内容"}]' } ], stream=True ) for chunk in completion: if chunk.choices[0].delta.content is not None: print(chunk.choices[0].dict()) #message=completion.choices[0].message.dict()['content'] #return message ''' file_object = self.client.files.create(file=Path(file_path), purpose="file-extract") file_content = self.client.files.content(file_id=file_object.id).text messages = [ { "role": "system", "content": "你是 Kimi,由 Moonshot AI 提供的人工智能助手,你更擅长中文和英文的对话。你会为用户提供安全,有帮助,准确的回答。同时,你会拒绝一切涉及恐怖主义,种族歧视,黄色暴力等问题的回答。Moonshot AI 为专有名词,不可翻译成其他语言。", }, { "role": "system", "content": file_content, }, {"role": "user", "content": "请写出总结"}, ] completion = self.client.chat.completions.create( model="moonshot-v1-32k", messages=messages, temperature=0.3, ) message=completion.choices[0].message.content return message ''' def get_single_round_completion(self, file_path, prompt, conversation): conversation.append_question(prompt) file_object = self.client.files.create(file=Path(file_path), purpose="file-extract") file_content = self.client.files.content(file_id=file_object.id).text messages = [ { "role": "system", "content": "你是 Kimi,由 Moonshot AI 提供的人工智能助手,你更擅长中文和英文的对话。你会为用户提供安全,有帮助,准确的回答。同时,你会拒绝一切涉及恐怖主义,种族歧视,黄色暴力等问题的回答。Moonshot AI 为专有名词,不可翻译成其他语言。", }, { "role": "system", "content": file_content, }, {"role": "user", "content": prompt}, ] completion = self.client.chat.completions.create( model="moonshot-v1-32k", messages=messages, temperature=0.3, ) message=completion.choices[0].message.content conversation.append_answer(message) return message, conversation def get_multi_round_completion(self, prompt, conversation, model='gpt-3.5-turbo'): conversation.append_question(prompt) prompts = conversation.get_prompts() response = openai.ChatCompletion.create( model=model, messages=prompts, temperature=0, max_tokens=2048, top_p=1, ) message = response.choices[0].message['content'] conversation.append_answer(message) return message, conversation class Conversation: def __init__(self, system_prompt='iii', num_of_round = 5): self.num_of_round = num_of_round self.history = [] self.initialized = False self.history.append({"role": "system", "content": system_prompt}) if len(system_prompt) > 0: #logger.info(f'Conversation initialized with system prompt: {system_prompt}') self.initialized = True def is_initialized(self): return self.initialized def append_question(self, question): self.history.append({"role": "user", "content": question}) def append_answer(self, answer): self.history.append({"role": "assistant", "content": answer}) if len(self.history) > self.num_of_round * 2: del self.history[1:3] def clear(self): self.history.clear() self.initialized = False def get_prompts(self): return self.history def round_size(self): return 0 if len(self.history) < 2 else len(self.hitory) - 1 def get_history_messages(self): return [(u['content'], b['content']) for u,b in zip(self.history[1::2], self.history[2::2])] chat_api = ChatgptAPI() client=OpenAI( api_key=os.environ.get("TONGYI_API_KEY"), # 替换成真实DashScope的API_KEY base_url="https://dashscope.aliyuncs.com/compatible-mode/v1", # 填写DashScopebase_url ) def predict_issue(password_input, user_in_file): if password_input != os.environ.get("USER_KEY"): return [(None, "Wrong password!")] file = client.files.create(file=Path(user_in_file), purpose="file-extract") completion = client.chat.completions.create( model="qwen-long", messages=[ { 'role': 'system', 'content': 'You are a helpful assistant.' }, { 'role': 'system', 'content': f'fileid://{file.id}' }, { 'role': 'user', 'content': '根据咨询文稿内容,完成咨询过程内容的梳理和总结,分别用一句话提炼出来访者的:1、主要问题:评估来访者当前遇到的问题呈现。\n 2、背景信息:评估来访者与主要问题相关的背景信息。\n 3、来访者主诉:评估来访者前来咨询的主要诉求和期待。\n 4、咨询动力:评估来访者前来咨询的主要动力。\n 任务:现在根据录音稿给出各项内容。注意:填写内容后停止一切输出,不做概括总结。' } ], stream=True ) history="" for chunk in completion: if chunk.choices[0].delta.content is not None: print(chunk.choices[0].dict()) history += chunk.choices[0].delta.content time.sleep(0.05) yield history def predict_mindmap(password_input, user_in_file): if password_input != os.environ.get("USER_KEY"): return [(None, "Wrong password!")] file = client.files.create(file=Path(user_in_file), purpose="file-extract") completion = client.chat.completions.create( model="qwen-long", messages=[ { 'role': 'system', 'content': 'You are a helpful assistant.' }, { 'role': 'system', 'content': f'fileid://{file.id}' }, { 'role': 'user', 'content': '你现在是心理咨询督导专家,现在要对咨询师的咨询内容进行督导。根据咨询过程进行分段和段落概括,至少包括2-4个主要分支,每个主要分支下有2-4个次要分支' } ], stream=True ) history="" for chunk in completion: if chunk.choices[0].delta.content is not None: print(chunk.choices[0].dict()) history += chunk.choices[0].delta.content time.sleep(0.05) yield history def predict_keywords(password_input, user_in_file): if password_input != os.environ.get("USER_KEY"): return [(None, "Wrong password!")] file = client.files.create(file=Path(user_in_file), purpose="file-extract") completion = client.chat.completions.create( model="qwen-long", messages=[ { 'role': 'system', 'content': 'You are a helpful assistant.' }, { 'role': 'system', 'content': f'fileid://{file.id}' }, { 'role': 'user', 'content': '根据咨询文稿内容,从以下角度分析来访者的特质:1、心理动力学:分析来访者的内心冲突、防御机制、情感状态以及它们如何影响行为。2、人格特质:分析来访的开放性、尽责性、外向性、宜人性、情绪稳定性、自尊、人格病理、适应能力、社会交往和动机与价值观。3、认知模式:评估来访者的思维模式,包括认知偏差、信念体系等。4、情绪状态:评估来访者的情绪稳定性、情绪表达方式以及情绪调节能力。5、行为模式:评估来访者的行为习惯、应对策略以及行为对当前问题的影响。6、应对资源和应对方式:评估来访者可用的资源和应对压力的方式。任务:分别从情绪、认知、行为和关系四个方面,提取来访者关键特质,并附上3-4个关键词。按以下格式输出:1、情绪 \n 关键特质:情绪波动明显 \n 关键词:焦虑、不安、恐惧' } ], stream=True ) history="" for chunk in completion: if chunk.choices[0].delta.content is not None: print(chunk.choices[0].dict()) history += chunk.choices[0].delta.content time.sleep(0.05) yield history def predict_dynamics(password_input, user_in_file): if password_input != os.environ.get("USER_KEY"): return [(None, "Wrong password!")] file = client.files.create(file=Path(user_in_file), purpose="file-extract") completion = client.chat.completions.create( model="qwen-long", messages=[ { 'role': 'system', 'content': 'You are a helpful assistant.' }, { 'role': 'system', 'content': f'fileid://{file.id}' }, { 'role': 'user', 'content': '你是心理咨询督导专家,现在要对咨询师的咨询内容进行督导。步骤1:打开并阅读我上传的文本文件的全部咨询内容,直到最后一个字符。步骤2 :依据以下框架对咨询内容评分(0分为完全不符合,10分为完全符合),记录评分和原因。若文本中未提及相关内容可忽略评分:1、开场:咨询师是否有效地开场,明确了本次咨询的目的和预期。2、建立关系:咨询师是否在咨询开始时建立了积极的工作关系。\n 客户是否感到被倾听和理解。3、倾听和沟通:咨询师是否展现出积极的倾听技巧,深入地探索来访者的感受,而不仅仅是停留在表面的认同。\n 沟通是否清晰、开放中立、减少引导,且鼓励来访者自己发现、表达,解释自己的感受和行为。4、情绪支持:是否帮助来访者识别和处理情绪,并积极地探索来访者的情绪背后的原因。\n 咨询师是否提供了适当的情绪相应与支持。5、目标聚焦:是否围绕既定目标进行咨询。\n 目标是否适合来访者当前的需求和情况,得到认同和参与。6、干预实施:咨询师是否使用了合适的干预策略。\n 干预和技术使用是否与客户的需要和目标相符。7、变化产生:评估来访者对会谈的反应,包括情感、认知和行为上的变化。 \n 评估在会谈过程中目标的实现程度,来访者是否有所进展。8、反馈和总结:咨询师是否提供了及时的反馈。\n 咨询师是否展现出对自己行为和反应的意识。9、会谈的结构:评估会谈是否有清晰的结构,包括引入、核心讨论和总结等部分。\n 评估会谈的流畅性,包括对话的连贯性和转换的自然性。10、结束:结束是否自然,是否有有效的总结,来访者是否得到了有用的反馈。\n 是否为下一次咨询或后续行动留下了清晰的指引,是否让来访者参与到这个总结过程中以增强来访者的参与感和咨询的个性化。步骤3:以上2步不输出,按以下格式输出:1、建立关系:\n 评分:,\n 原因(尽量引用相关原文分析):' } ], stream=True ) history="" for chunk in completion: if chunk.choices[0].delta.content is not None: print(chunk.choices[0].dict()) history += chunk.choices[0].delta.content time.sleep(0.05) yield history def predict_complaint(password_input, user_in_file): if password_input != os.environ.get("USER_KEY"): return [(None, "Wrong password!")] file = client.files.create(file=Path(user_in_file), purpose="file-extract") completion = client.chat.completions.create( model="qwen-long", messages=[ { 'role': 'system', 'content': 'You are a helpful assistant.' }, { 'role': 'system', 'content': f'fileid://{file.id}' }, { 'role': 'user', 'content': '作为资深的心理督导专家,你在进行咨询主诉和会谈目标概括时,会采用以下框架来评估和理解来访者的情况:1、案例描述: \n主要问题:评估来访者当前遇到的问题呈现。\n 背景信息:评估来访者与主要问题相关的背景信息。\n 来访者主诉:评估来访者前来咨询的主要诉求和期待。\n 咨询动力:评估来访者前来咨询的主要动力。\n 任务:现在根据录音稿给出各项内容。注意:填写内容后停止一切输出,不做概括总结。' } ], stream=True ) history="" for chunk in completion: if chunk.choices[0].delta.content is not None: print(chunk.choices[0].dict()) history += chunk.choices[0].delta.content time.sleep(0.05) yield history def predict_concept(password_input, user_in_file): if password_input != os.environ.get("USER_KEY"): return [(None, "Wrong password!")] file = client.files.create(file=Path(user_in_file), purpose="file-extract") completion = client.chat.completions.create( model="qwen-long", messages=[ { 'role': 'system', 'content': 'You are a helpful assistant.' }, { 'role': 'system', 'content': f'fileid://{file.id}' }, { 'role': 'user', 'content': '作为资深的心理督导专家,你在进行个案概念化时,会采用以下框架来评估和理解来访者的情况:1、人口统计学信息:包括来访者的年龄、性别、民族、教育背景、职业状态等基本信息。2、发展史:评估来访者的成长背景,包括家庭环境、早期经历、教育历程等。3、心理社会历史:包括来访者的重要生活事件、人际关系、社会支持系统等。4、心理健康史:评估来访者的心理健康状况,包括过去和现在的心理问题、治疗历史等。5、心理动力学:分析来访者的内心冲突、防御机制、情感状态以及它们如何影响行为。6、格特质:分析来访的开放性、尽责性、外向性、宜人性、情绪稳定性、自尊、人格病理、适应能力、社会交往、动机与价值观。7、认知模式:评估来访者的思维模式,包括认知偏差、信念体系等。8、情绪状态:评估来访者的情绪稳定性、情绪表达方式以及情绪调节能力。9、行为模式:评估来访者的行为习惯、应对策略以及行为对当前问题的影响。10、应对资源和应对方式:评估来访者可用的资源和应对压力的方式。11、当前生活状况:评估来访者目前的生活状况,如工作、学习、家庭生活、社交人际活动等。12、诊断印象:列出相关的诊断印象,包括DSM代码和轴。13、风险评估:评估来访者可能存在的风险因素,如自杀风险、自我伤害风险等。任务:现在根据录音稿给出各项评估,涉及具体内容时使用以下格式引用来访者回话的相关段落({「引用」:…}),并给出概括总结。' } ], stream=True ) history="" for chunk in completion: if chunk.choices[0].delta.content is not None: print(chunk.choices[0].dict()) history += chunk.choices[0].delta.content time.sleep(0.05) yield history def predict_plan(password_input, user_in_file): if password_input != os.environ.get("USER_KEY"): return [(None, "Wrong password!")] file = client.files.create(file=Path(user_in_file), purpose="file-extract") completion = client.chat.completions.create( model="qwen-long", messages=[ { 'role': 'system', 'content': 'You are a helpful assistant.' }, { 'role': 'system', 'content': f'fileid://{file.id}' }, { 'role': 'user', 'content': '你是资深的心理督导专家,你在制定未来咨询计划的规划时,通常会依据以下几个框架维度来进行:1、治疗计划:维度1:当前状况评估 - 根据本次会谈内容,评估来访者的情绪状态、认知模式、行为表现以及社会功能。 \n 维度2:目标细化 - 将长远的治疗目标细化为短期可达成的小目标,确保目标的可操作性和逐步实现性。\n维度3:干预措施选择 - 根据来访者的需求和偏好,选择合适的心理干预措施,如认知行为治疗、心理动力学治疗、解决问题治疗等。\n 2、下次会谈目标:基于咨询内容,提取咨询师和来访者在咨询中达成一致,双方共同愿意努力的核心会谈目标。1-3点。\n 维度1:回顾与整合 - 回顾本次会谈的关键点,整合来访者的反馈,强化治疗联盟。\n维度2:未解决议题深入探讨 - 针对本次咨询中未完全解决的问题或新出现的问题,进行更深入的探讨和分析。\n 维度3:技能练习与应用 - 教授来访者特定的应对技巧或心理调适技能,并鼓励在日常生活中的实践应用。\n 任务:现在根据录音稿给出各项评估,并给出总结' } ], stream=True ) history="" for chunk in completion: if chunk.choices[0].delta.content is not None: print(chunk.choices[0].dict()) history += chunk.choices[0].delta.content time.sleep(0.05) yield history def predict_highlight(password_input, user_in_file): if password_input != os.environ.get("USER_KEY"): return [(None, "Wrong password!")] file = client.files.create(file=Path(user_in_file), purpose="file-extract") completion = client.chat.completions.create( model="qwen-long", messages=[ { 'role': 'system', 'content': 'You are a helpful assistant.' }, { 'role': 'system', 'content': f'fileid://{file.id}' }, { 'role': 'user', 'content': '你是心理咨询督导专家,现在要对咨询师的咨询内容进行督导。不要依赖咨询师的回话,因为它可能是不正确的。step by step完成以下步骤:\n 步骤1-打开并阅读我上传的文本文件的全部内容,直到最后一个字符 \n 步骤2-在全文中摘取来访者的【关键性发言】,不要仅摘录文本前半部分的发言,最终选出其中最需要被讨论的3-4条,记录发言结束后第一个咨询师发起的回复内容为【咨询师的回复】 \n 步骤3-针对关键性发言,给出合适的【督导回话内容】 \n 步骤4-对比【督导回话内容】和【咨询师的回复】,并给每句回打分(0分为与督导回话方案完全不一致,10分与督导回话方案完全一致) \n 步骤5-以上4步仅执行不输出,仅按以下格式输出:- 关键性发言n:,\n - 来访者:,\n , - 督导回话方案:, \n , - 咨询师的回复: ,\n , - 评分:x/10 \n ,- 修改原因: ' } ], stream=True ) history="" for chunk in completion: if chunk.choices[0].delta.content is not None: print(chunk.choices[0].dict()) history += chunk.choices[0].delta.content time.sleep(0.05) yield history #conversation = chat_api.get_summary(user_in_file) #return conversation with gr.Blocks(css="#chatbot{height:350px} .overflow-y-auto{height:600px}") as demo: with gr.Row(): system_in_txt = gr.Textbox(lines=1, label="User Name:", placeholder="Enter user name") password_in_txt = gr.Textbox(lines=1, label="Password:", placeholder="Enter password") with gr.Row(): with gr.Column(scale=1, min_width=50): user_in_file = gr.File(label="Upload File") #submit_button = gr.Button("Submit") issue_button = gr.Button("咨询主诉") mindmap_button = gr.Button("思维导图") keywords_button = gr.Button("咨询关键词") dynamics_button = gr.Button("会谈动态") concept_button = gr.Button("个案概念化") highlight_button = gr.Button("对话改善") plan_button = gr.Button("后续计划") with gr.Column(scale=2): system_in_txt = gr.Textbox(lines=30, label="Output Text:") issue_button.click(fn=predict_issue, inputs=[password_in_txt, user_in_file], outputs=[system_in_txt]) mindmap_button.click(fn=predict_mindmap, inputs=[password_in_txt, user_in_file], outputs=[system_in_txt]) keywords_button.click(fn=predict_keywords, inputs=[password_in_txt, user_in_file], outputs=[system_in_txt]) dynamics_button.click(fn=predict_dynamics, inputs=[password_in_txt, user_in_file], outputs=[system_in_txt]) ##complaint_button.click(fn=predict_complaint, inputs=[password_in_txt, user_in_file], outputs=[system_in_txt]) concept_button.click(fn=predict_concept, inputs=[password_in_txt, user_in_file], outputs=[system_in_txt]) highlight_button.click(fn=predict_highlight, inputs=[password_in_txt, user_in_file], outputs=[system_in_txt]) plan_button.click(fn=predict_plan, inputs=[password_in_txt, user_in_file], outputs=[system_in_txt]) #submit_button.click(predict, [system_in_txt, password_in_txt, user_in_file, user_in_txt, conversation], [chatbot, conversation, user_in_txt]) #reset_button.click(clear_history, [conversation], [chatbot, conversation], queue=False) if __name__ == "__main__": demo.launch()