chat_model.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  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 = 1
  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. if i% 2 == 0:
  45. recent += recent_list[i] + ":"
  46. else:
  47. recent += recent_list[i] + "\n"
  48. print("-------------recent---------------")
  49. print(recent)
  50. messages = [{'role': 'system', 'content': prompt + recent}]
  51. messages.append({'role': 'user', 'content': word})
  52. try:
  53. ans = groq_chat(messages)
  54. except Exception as e:
  55. ans = siliflow_chat(messages)
  56. ans = ans.lstrip()
  57. ans = ans.lstrip("猫猫:")
  58. while True:
  59. if ans.endswith("\n") or ans.endswith(" "):
  60. ans = ans[:-1]
  61. else:
  62. break
  63. return ans
  64. def groq_chat(messages, model = "deepseek-r1-distill-llama-70b"):
  65. """
  66. 主对话通道,https://api.gxx12138.space/groq/v1
  67. """
  68. client = OpenAI(
  69. base_url="https://api.gxx12138.space/groq/v1",
  70. api_key=groq_key
  71. )
  72. completion = client.chat.completions.create(
  73. model=model,
  74. stream=True,
  75. messages=messages
  76. )
  77. ans = ""
  78. for chunk in completion:
  79. # print(chunk)
  80. if chunk.choices[0].delta.content:
  81. ans += chunk.choices[0].delta.content
  82. start_tag = "<think>"
  83. end_tag = "</think>"
  84. text = ans
  85. while start_tag in text and end_tag in text:
  86. start_idx = text.find(start_tag)
  87. end_idx = text.find(end_tag) + len(end_tag)
  88. text = text[:start_idx] + text[end_idx:]
  89. # 清理多余的空白行
  90. cleaned_text = "\n".join([line for line in text.split("\n") if line.strip()])
  91. return cleaned_text.strip()
  92. def siliflow_chat(messages, model = "THUDM/glm-4-9b-chat"):
  93. """
  94. 备用对话通道,https://api.siliconflow.cn/v1'
  95. """
  96. client = OpenAI(
  97. base_url='https://api.siliconflow.cn/v1',
  98. api_key=siliflow_key
  99. )
  100. try:
  101. print("硅基模型正常运作")
  102. # 发送AI请求
  103. # THUDM/glm-4-9b-chat google/gemma-2-9b-it
  104. response = client.chat.completions.create(
  105. model=model,
  106. messages=messages,
  107. stream=False,
  108. temperature=0.8,
  109. )
  110. ans = response.choices[0].message.content
  111. except Exception as e:
  112. print("硅基模型爆了")
  113. ans = ""
  114. return ans
  115. def AI_get_picprompt(group_id):
  116. """
  117. 群聊id自动获取群聊记录来获取绘画提示词
  118. """
  119. global pro_good
  120. # 加载聊天记录
  121. folder_path = '群聊记录'
  122. file_path = os.path.join(folder_path, str(group_id) + '.csv')
  123. df = pd.read_csv(file_path)
  124. recent = ""
  125. for i in range(len(df) - 4, len(df)):
  126. recent += str(df.loc[i, 'user_name']) + ":" + str(df.loc[i, 'message']) + "\n"
  127. messages = [{'role': 'system', 'content': prompt_pic}]
  128. messages.append({'role': 'user', 'content': recent})
  129. ans = groq_chat(messages)
  130. return pro_good + ans.strip().replace("\n", "") + ","
  131. def AI_sendphoto_ornot(event):
  132. """
  133. AI思考链,判断是否应该发送图片
  134. """
  135. messages = [{'role': 'system', 'content': prompt_chpic}]
  136. messages.append({'role': 'user', 'content': event})
  137. client = OpenAI(
  138. base_url='https://api.siliconflow.cn/v1',
  139. api_key=siliflow_key
  140. )
  141. # 发送AI请求
  142. response = client.chat.completions.create(
  143. model="THUDM/glm-4-9b-chat",
  144. messages=messages,
  145. stream=False,
  146. temperature=0.7,
  147. )
  148. ans = response.choices[0].message.content
  149. ans = ans.lstrip()
  150. print(f"图片发送决定:{ans}")
  151. return ans
  152. def AI_lora_getpic_prompt(word):
  153. """
  154. 群聊id自动获取群聊记录来获取绘画提示词
  155. 版本2
  156. """
  157. messages = [{'role': 'system', 'content': prompt_lora}]
  158. messages.append({'role': 'user', 'content': word})
  159. ans = siliflow_chat(messages).replace(", ", ",")
  160. return ans.strip().replace("\n", "") + ","
  161. def detect_tool(message):
  162. """
  163. 新方法,编写中
  164. """
  165. model = "llama-3.3-70b-versatile"