chat_model.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. import pandas as pd
  2. from openai import OpenAI
  3. import requests
  4. import json
  5. import re
  6. from pic_read import pic_see
  7. from config import config_get,key_get
  8. import os
  9. # 全局变量在这里改写:
  10. max_length = 20
  11. max_pic_see = 0
  12. prompt_pic = config_get("prompt_pic")
  13. prompt_lora = config_get("prompt_lora")
  14. prompt_chpic = config_get("prompt_chpic")
  15. pro_good = "solo,cat ears,black_hair,black_eye,"
  16. pro_bad = config_get("pro_bad")
  17. groq_key = key_get("groq")
  18. siliflow_key = key_get("siliflow")
  19. def AI_chat(group_id ,word ,prompt):
  20. """
  21. 猫猫人格,输入群号获取聊天记录,输入问题获取对话对象,返回字符串
  22. """
  23. # 加载聊天记录
  24. folder_path = '群聊记录'
  25. file_path = os.path.join(folder_path, str(group_id) + '.csv')
  26. df = pd.read_csv(file_path)
  27. recent = str("")
  28. recent_list = []
  29. for i in range(len(df)):
  30. if i >= len(df ) -max_length:
  31. recent_list.append(str(df.loc[i ,'user_name']))
  32. recent_list.append(str(df.loc[i, 'message']))
  33. pic_num = 0
  34. list_num = len(recent_list)
  35. for i in reversed(recent_list):
  36. list_num = list_num -1
  37. if pic_num >= max_pic_see:
  38. break
  39. if str(i).startswith("图片内容:"):
  40. url = i[5:]
  41. recent_list[list_num] = "发送了一张图片," + str(pic_see(url)).replace("\n", "")
  42. pic_num +=1
  43. for i in range(len(recent_list)):
  44. #新增逻辑,处理掉所有没必要的链接内容
  45. if recent_list[i].startswith("图片内容:"):
  46. recent_list[i] = "图片内容"
  47. if i% 2 == 0:
  48. recent += recent_list[i] + ":"
  49. else:
  50. recent += recent_list[i] + "\n"
  51. print("-------------recent---------------")
  52. print(recent)
  53. messages = [{'role': 'system', 'content': prompt + recent}]
  54. messages.append({'role': 'user', 'content': word})
  55. try:
  56. ans = groq_chat(messages)
  57. except Exception as e:
  58. ans = siliflow_chat(messages)
  59. ans = ans.lstrip()
  60. ans = ans.lstrip("猫猫:")
  61. while True:
  62. if ans.endswith("\n") or ans.endswith(" "):
  63. ans = ans[:-1]
  64. else:
  65. break
  66. return ans
  67. def groq_chat(messages, model = "qwen/qwen3-32b"):
  68. """
  69. 主对话通道,https://api.gxx12138.space/groq/v1
  70. """
  71. client = OpenAI(
  72. base_url="https://api.gxx12138.space/groq/v1",
  73. api_key=groq_key
  74. )
  75. completion = client.chat.completions.create(
  76. model=model,
  77. stream=True,
  78. messages=messages
  79. )
  80. ans = ""
  81. for chunk in completion:
  82. # print(chunk)
  83. if chunk.choices[0].delta.content:
  84. ans += chunk.choices[0].delta.content
  85. start_tag = "<think>"
  86. end_tag = "</think>"
  87. text = ans
  88. while start_tag in text and end_tag in text:
  89. start_idx = text.find(start_tag)
  90. end_idx = text.find(end_tag) + len(end_tag)
  91. text = text[:start_idx] + text[end_idx:]
  92. # 清理多余的空白行
  93. cleaned_text = "\n".join([line for line in text.split("\n") if line.strip()])
  94. return cleaned_text.strip()
  95. def siliflow_chat(messages, model = "THUDM/GLM-4-9B-0414"):
  96. """
  97. 备用对话通道,https://api.siliconflow.cn/v1'
  98. """
  99. client = OpenAI(
  100. base_url='https://api.siliconflow.cn/v1',
  101. api_key=siliflow_key
  102. )
  103. try:
  104. print("硅基模型正常运作")
  105. # 发送AI请求
  106. # THUDM/glm-4-9b-chat google/gemma-2-9b-it
  107. response = client.chat.completions.create(
  108. model=model,
  109. messages=messages,
  110. stream=False,
  111. temperature=0.8,
  112. )
  113. ans = response.choices[0].message.content
  114. except Exception as e:
  115. print("硅基模型爆了")
  116. ans = ""
  117. return ans
  118. def AI_get_picprompt(group_id):
  119. """
  120. 群聊id自动获取群聊记录来获取绘画提示词
  121. """
  122. global pro_good
  123. # 加载聊天记录
  124. folder_path = '群聊记录'
  125. file_path = os.path.join(folder_path, str(group_id) + '.csv')
  126. df = pd.read_csv(file_path)
  127. recent = ""
  128. for i in range(len(df) - 4, len(df)):
  129. recent += str(df.loc[i, 'user_name']) + ":" + str(df.loc[i, 'message']) + "\n"
  130. messages = [{'role': 'system', 'content': prompt_pic}]
  131. messages.append({'role': 'user', 'content': recent})
  132. ans = groq_chat(messages)
  133. return pro_good + ans.strip().replace("\n", "") + ","
  134. def AI_sendphoto_ornot(event):
  135. """
  136. AI思考链,判断是否应该发送图片
  137. """
  138. messages = [{'role': 'system', 'content': prompt_chpic}]
  139. messages.append({'role': 'user', 'content': event})
  140. client = OpenAI(
  141. base_url='https://api.siliconflow.cn/v1',
  142. api_key=siliflow_key
  143. )
  144. # 发送AI请求
  145. response = client.chat.completions.create(
  146. model="THUDM/glm-4-9b-chat",
  147. messages=messages,
  148. stream=False,
  149. temperature=0.7,
  150. )
  151. ans = response.choices[0].message.content
  152. ans = ans.lstrip()
  153. print(f"图片发送决定:{ans}")
  154. return ans
  155. def AI_lora_getpic_prompt(word):
  156. """
  157. 群聊id自动获取群聊记录来获取绘画提示词
  158. 版本2
  159. """
  160. if len(word) == 0:
  161. return ""
  162. messages = [{'role': 'system', 'content': prompt_lora}]
  163. messages.append({'role': 'user', 'content': word})
  164. ans = siliflow_chat(messages).replace(", ", ",")
  165. return ans.strip().replace("\n", "") + ","
  166. def get_ja_trans(group_id):
  167. """
  168. 返回该群中猫猫说的最后一句话的日语翻译,如果此群中还没说过话则返回失败
  169. """
  170. # 加载聊天记录
  171. folder_path = '群聊记录'
  172. file_path = os.path.join(folder_path, str(group_id) + '.csv')
  173. df = pd.read_csv(file_path)
  174. # 获取最后一条猫猫发送的消息
  175. cat_msg = ""
  176. for i in range(len(df) - 1, -1, -1):
  177. if df.loc[i, 'user_name'] == "猫猫":
  178. cat_msg = df.loc[i, 'message']
  179. break
  180. if cat_msg == "":
  181. return "失败"
  182. # 开始进行翻译
  183. prompt = config_get('pro_trans') + cat_msg
  184. messages = [{'role': 'user', 'content': prompt}]
  185. # ans = siliflow_chat(messages, "deepseek-ai/DeepSeek-V3")
  186. ans = siliflow_chat(messages)
  187. return ans.strip().replace("\n", "")
  188. def detect_tool(message):
  189. """
  190. 新方法,编写中
  191. """
  192. model = "llama-3.3-70b-versatile"
  193. if __name__ == "__main__":
  194. # 测试用例1:简单问候消息
  195. test_messages1 = [
  196. {"role": "system", "content": "你是一个友好的助手,用简洁的语言回答问题。"},
  197. {"role": "user", "content": "你好!请介绍一下你自己。"}
  198. ]
  199. print("测试用例1:简单问候消息")
  200. try:
  201. response1 = groq_chat(test_messages1)
  202. print("响应结果:")
  203. print(response1)
  204. print("测试用例1执行成功\n")
  205. except Exception as e:
  206. print(f"测试用例1执行失败:{str(e)}\n")
  207. # 测试用例2:包含特殊标记的消息(测试清理功能)
  208. test_messages2 = [
  209. {"role": "system", "content": "直接重复用户的消息"},
  210. {"role": "user", "content": "这是一段包含特殊标记的文本:需要移除的内容<|FunctionCallEnd|>请检查是否能正确清理。"}
  211. ]