chat.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. import json
  2. import os
  3. import base64
  4. import httpx
  5. import asyncio
  6. from typing import Optional, List, Dict, Any, Union
  7. from .feishu_client import FeishuClient, FeishuDomain
  8. from agent.tools import tool, ToolResult, ToolContext
  9. # 从环境变量获取飞书配置
  10. # 也可以在此设置硬编码的默认值,但推荐使用环境变量
  11. FEISHU_APP_ID = os.getenv("FEISHU_APP_ID", "cli_a90fe317987a9cc9")
  12. FEISHU_APP_SECRET = os.getenv("FEISHU_APP_SECRET", "nn2dWuXTiRA2N6xodbm4g0qz1AfM2ayi")
  13. CONTACTS_FILE = os.path.join(os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "..", "..")), "config", "feishu_contacts.json")
  14. CHAT_HISTORY_DIR = os.path.join(os.path.dirname(__file__), "chat_history")
  15. UNREAD_SUMMARY_FILE = os.path.join(CHAT_HISTORY_DIR, "chat_summary.json")
  16. # ==================== 一、文件内使用的功能函数 ====================
  17. def load_contacts() -> List[Dict[str, Any]]:
  18. """读取 contacts.json 中的所有联系人"""
  19. if not os.path.exists(CONTACTS_FILE):
  20. return []
  21. try:
  22. with open(CONTACTS_FILE, 'r', encoding='utf-8') as f:
  23. return json.load(f)
  24. except Exception:
  25. return []
  26. def save_contacts(contacts: List[Dict[str, Any]]):
  27. """保存联系人信息到 contacts.json"""
  28. try:
  29. with open(CONTACTS_FILE, 'w', encoding='utf-8') as f:
  30. json.dump(contacts, f, ensure_ascii=False, indent=2)
  31. except Exception as e:
  32. print(f"保存联系人失败: {e}")
  33. def list_contacts_info() -> List[Dict[str, str]]:
  34. """
  35. 1. 列出所有联系人信息
  36. 读取 contacts.json 中的每一个联系人的 name、description,以字典列表返回
  37. """
  38. contacts = load_contacts()
  39. return [{"name": c.get("name", ""), "description": c.get("description", "")} for c in contacts]
  40. def get_contact_full_info(name: str) -> Optional[Dict[str, Any]]:
  41. """
  42. 2. 根据联系人名称获取联系人完整字典信息
  43. 从 contacts.json 中读取每一个联系人做名称匹配,返回数据中的所有字段为一个字典对象
  44. """
  45. contacts = load_contacts()
  46. for c in contacts:
  47. if c.get("name") == name:
  48. return c
  49. return None
  50. def get_contact_by_id(id_value: str) -> Optional[Dict[str, Any]]:
  51. """根据 chat_id 或 open_id 获取联系人信息"""
  52. contacts = load_contacts()
  53. for c in contacts:
  54. if c.get("chat_id") == id_value or c.get("open_id") == id_value:
  55. return c
  56. return None
  57. def update_contact_chat_id(name: str, chat_id: str):
  58. """
  59. 3. 更新某一个联系人的 chat_id
  60. """
  61. contacts = load_contacts()
  62. updated = False
  63. for c in contacts:
  64. if c.get("name") == name:
  65. if not c.get("chat_id"):
  66. c["chat_id"] = chat_id
  67. updated = True
  68. break
  69. if updated:
  70. save_contacts(contacts)
  71. # ==================== 二、聊天记录文件管理 ====================
  72. def _ensure_chat_history_dir():
  73. if not os.path.exists(CHAT_HISTORY_DIR):
  74. os.makedirs(CHAT_HISTORY_DIR)
  75. def get_chat_file_path(contact_name: str) -> str:
  76. _ensure_chat_history_dir()
  77. return os.path.join(CHAT_HISTORY_DIR, f"chat_{contact_name}.json")
  78. def load_chat_history(contact_name: str) -> List[Dict[str, Any]]:
  79. path = get_chat_file_path(contact_name)
  80. if os.path.exists(path):
  81. try:
  82. with open(path, 'r', encoding='utf-8') as f:
  83. return json.load(f)
  84. except Exception:
  85. return []
  86. return []
  87. def save_chat_history(contact_name: str, history: List[Dict[str, Any]]):
  88. path = get_chat_file_path(contact_name)
  89. try:
  90. with open(path, 'w', encoding='utf-8') as f:
  91. json.dump(history, f, ensure_ascii=False, indent=2)
  92. except Exception as e:
  93. print(f"保存聊天记录失败: {e}")
  94. def update_unread_count(contact_name: str, increment: int = 1, reset: bool = False):
  95. """更新未读消息摘要"""
  96. _ensure_chat_history_dir()
  97. summary = {}
  98. if os.path.exists(UNREAD_SUMMARY_FILE):
  99. try:
  100. with open(UNREAD_SUMMARY_FILE, 'r', encoding='utf-8') as f:
  101. summary = json.load(f)
  102. except Exception:
  103. summary = {}
  104. if reset:
  105. summary[contact_name] = 0
  106. else:
  107. summary[contact_name] = summary.get(contact_name, 0) + increment
  108. try:
  109. with open(UNREAD_SUMMARY_FILE, 'w', encoding='utf-8') as f:
  110. json.dump(summary, f, ensure_ascii=False, indent=2)
  111. except Exception as e:
  112. print(f"更新未读摘要失败: {e}")
  113. # ==================== 三、@tool 工具 ====================
  114. @tool(
  115. display={
  116. "zh": {
  117. "name": "获取飞书联系人列表",
  118. "params": {}
  119. },
  120. "en": {
  121. "name": "Get Feishu Contact List",
  122. "params": {}
  123. }
  124. }
  125. )
  126. async def feishu_get_contact_list(context: Optional[ToolContext] = None) -> ToolResult:
  127. """
  128. 获取所有联系人的名称和描述。
  129. Args:
  130. context: 工具执行上下文(可选)
  131. """
  132. contacts = list_contacts_info()
  133. return ToolResult(
  134. title="获取联系人列表成功",
  135. output=json.dumps(contacts, ensure_ascii=False, indent=2),
  136. metadata={"contacts": contacts}
  137. )
  138. @tool(
  139. display={
  140. "zh": {
  141. "name": "给飞书联系人发送消息",
  142. "params": {
  143. "contact_name": "联系人名称",
  144. "content": "消息内容。OpenAI 多模态格式列表 (例如: [{'type': 'text', 'text': '你好'}, {'type': 'image_url', 'image_url': {'url': '...'}}])"
  145. }
  146. },
  147. "en": {
  148. "name": "Send Message to Feishu Contact",
  149. "params": {
  150. "contact_name": "Contact Name",
  151. "content": "Message content. OpenAI multimodal list format."
  152. }
  153. }
  154. }
  155. )
  156. async def feishu_send_message_to_contact(
  157. contact_name: str,
  158. content: Any,
  159. context: Optional[ToolContext] = None
  160. ) -> ToolResult:
  161. """
  162. 给指定的联系人发送消息。支持发送文本和图片,OpenAI 多模态格式,会自动转换为飞书相应的格式并发起多次发送。
  163. Args:
  164. contact_name: 飞书联系人的名称
  165. content: 消息内容。OpenAI 多模态列表格式。
  166. """
  167. contact = get_contact_full_info(contact_name)
  168. if not contact:
  169. return ToolResult(title="发送失败", output=f"未找到联系人: {contact_name}", error="Contact not found")
  170. client = FeishuClient(app_id=FEISHU_APP_ID, app_secret=FEISHU_APP_SECRET)
  171. # 确定接收者 ID (优先使用 chat_id,否则使用 open_id)
  172. receive_id = contact.get("chat_id") or contact.get("open_id") or contact.get("user_id")
  173. if not receive_id:
  174. return ToolResult(title="发送失败", output="联系人 ID 信息缺失", error="Receiver ID not found in contacts.json")
  175. # 如果 content 是字符串,尝试解析为 JSON
  176. if isinstance(content, str):
  177. try:
  178. parsed = json.loads(content)
  179. if isinstance(parsed, (list, dict)):
  180. content = parsed
  181. except (json.JSONDecodeError, TypeError):
  182. pass
  183. try:
  184. last_res = None
  185. if isinstance(content, str):
  186. last_res = client.send_message(to=receive_id, text=content)
  187. elif isinstance(content, list):
  188. for item in content:
  189. item_type = item.get("type")
  190. if item_type == "text":
  191. last_res = client.send_message(to=receive_id, text=item.get("text", ""))
  192. elif item_type == "image_url":
  193. img_info = item.get("image_url", {})
  194. url = img_info.get("url")
  195. if url.startswith("data:image"):
  196. # 处理 base64 图片
  197. try:
  198. if "," in url:
  199. _, encoded = url.split(",", 1)
  200. else:
  201. encoded = url
  202. image_bytes = base64.b64decode(encoded)
  203. last_res = client.send_image(to=receive_id, image=image_bytes)
  204. except Exception as e:
  205. print(f"解析 base64 图片失败: {e}")
  206. else:
  207. # 处理网络 URL
  208. try:
  209. async with httpx.AsyncClient() as httpx_client:
  210. img_resp = await httpx_client.get(url, timeout=15.0)
  211. img_resp.raise_for_status()
  212. last_res = client.send_image(to=receive_id, image=img_resp.content)
  213. except Exception as e:
  214. print(f"下载图片失败: {e}")
  215. elif isinstance(content, dict):
  216. # 如果是单块格式也支持一下
  217. item_type = content.get("type")
  218. if item_type == "text":
  219. last_res = client.send_message(to=receive_id, text=content.get("text", ""))
  220. elif item_type == "image_url":
  221. # ... 逻辑与上面类似,为了简洁这里也可以统一转成 list 处理
  222. content = [content]
  223. # 此处递归或重写逻辑,这里选择简单地重新判断
  224. return await feishu_send_message_to_contact(contact_name, content, context)
  225. else:
  226. return ToolResult(title="发送失败", output="不支持的内容格式", error="Invalid content format")
  227. if last_res:
  228. # 更新 chat_id
  229. update_contact_chat_id(contact_name, last_res.chat_id)
  230. # [待开启] 发送即记录:为了维护完整的聊天记录,将机器人发出的消息也保存到本地文件
  231. try:
  232. history = load_chat_history(contact_name)
  233. history.append({
  234. "role": "assistant",
  235. "message_id": last_res.message_id,
  236. "content": content if isinstance(content, list) else [{"type": "text", "text": content}]
  237. })
  238. save_chat_history(contact_name, history)
  239. # 机器人回复了,将该联系人的未读计数重置为 0
  240. update_unread_count(contact_name, reset=True)
  241. except Exception as e:
  242. print(f"记录发送的消息失败: {e}")
  243. return ToolResult(
  244. title=f"消息已成功发送至 {contact_name}",
  245. output=f"发送成功。消息 ID: {last_res.message_id}",
  246. metadata={"message_id": last_res.message_id, "chat_id": last_res.chat_id}
  247. )
  248. return ToolResult(title="发送失败", output="没有执行成功的发送操作")
  249. except Exception as e:
  250. return ToolResult(title="发送异常", output=str(e), error=str(e))
  251. @tool(
  252. display={
  253. "zh": {
  254. "name": "获取飞书联系人回复",
  255. "params": {
  256. "contact_name": "联系人名称",
  257. "wait_time_seconds": "可选,如果当前没有新回复,则最多等待指定的秒数。在等待期间会每秒检查一次,一旦有新回复则立即返回。超过时长仍无回复则返回空。"
  258. }
  259. },
  260. "en": {
  261. "name": "Get Feishu Contact Replies",
  262. "params": {
  263. "contact_name": "Contact Name",
  264. "wait_time_seconds": "Optional. If there are no new replies, wait up to the specified number of seconds. It will check every second and return immediately if a new reply is detected. If no reply is received after the duration, it returns empty."
  265. }
  266. }
  267. }
  268. )
  269. async def feishu_get_contact_replies(
  270. contact_name: str,
  271. wait_time_seconds: Optional[int] = None,
  272. context: Optional[ToolContext] = None
  273. ) -> ToolResult:
  274. """
  275. 获取指定联系人的最新回复消息。
  276. 返回的数据格式为 OpenAI 多模态消息内容列表。
  277. 只抓取自上一个机器人消息之后的用户回复。
  278. Args:
  279. contact_name: 飞书联系人的名称
  280. wait_time_seconds: 可选的最大轮询等待时间。如果暂时没有新回复,将每秒检查一次直到有回复或超时。
  281. context: 工具执行上下文(可选)
  282. """
  283. contact = get_contact_full_info(contact_name)
  284. if not contact:
  285. return ToolResult(title="获取失败", output=f"未找到联系人: {contact_name}", error="Contact not found")
  286. chat_id = contact.get("chat_id")
  287. if not chat_id:
  288. return ToolResult(title="获取失败", output=f"联系人 {contact_name} 尚未建立会话 (无 chat_id)", error="No chat_id")
  289. client = FeishuClient(app_id=FEISHU_APP_ID, app_secret=FEISHU_APP_SECRET)
  290. try:
  291. def get_replies():
  292. msg_list_res = client.get_message_list(chat_id=chat_id)
  293. if not msg_list_res or "items" not in msg_list_res:
  294. return []
  295. openai_blocks = []
  296. # 遍历消息列表 (最新的在前)
  297. for msg in msg_list_res["items"]:
  298. if msg.get("sender_type") == "app":
  299. # 碰到机器人的消息即停止
  300. break
  301. content_blocks = _convert_feishu_msg_to_openai_content(client, msg)
  302. openai_blocks.extend(content_blocks)
  303. # 反转列表以保持时间正序 (旧 -> 新)
  304. openai_blocks.reverse()
  305. return openai_blocks
  306. openai_blocks = get_replies()
  307. # 如果初始没有获取到回复,且设置了等待时间,则开始轮询
  308. if not openai_blocks and wait_time_seconds and wait_time_seconds > 0:
  309. for _ in range(int(wait_time_seconds)):
  310. await asyncio.sleep(1)
  311. openai_blocks = get_replies()
  312. if openai_blocks:
  313. break
  314. return ToolResult(
  315. title=f"获取 {contact_name} 回复成功",
  316. output=json.dumps(openai_blocks, ensure_ascii=False, indent=2) if openai_blocks else "目前没有新的用户回复",
  317. metadata={"replies": openai_blocks}
  318. )
  319. except Exception as e:
  320. return ToolResult(title="获取回复异常", output=str(e), error=str(e))
  321. def _convert_feishu_msg_to_openai_content(client: FeishuClient, msg: Dict[str, Any]) -> List[Dict[str, Any]]:
  322. """将单条飞书消息内容转换为 OpenAI 多模态格式块列表"""
  323. blocks = []
  324. msg_type = msg.get("content_type")
  325. raw_content = msg.get("content", "")
  326. message_id = msg.get("message_id")
  327. if msg_type == "text":
  328. blocks.append({"type": "text", "text": raw_content})
  329. elif msg_type == "image":
  330. try:
  331. content_dict = json.loads(raw_content)
  332. image_key = content_dict.get("image_key")
  333. if image_key and message_id:
  334. img_bytes = client.download_message_resource(
  335. message_id=message_id,
  336. file_key=image_key,
  337. resource_type="image"
  338. )
  339. b64_str = base64.b64encode(img_bytes).decode('utf-8')
  340. blocks.append({
  341. "type": "image_url",
  342. "image_url": {"url": f"data:image/png;base64,{b64_str}"}
  343. })
  344. except Exception as e:
  345. print(f"转换图片消息失败: {e}")
  346. blocks.append({"type": "text", "text": "[图片内容获取失败]"})
  347. elif msg_type == "post":
  348. blocks.append({"type": "text", "text": raw_content})
  349. else:
  350. blocks.append({"type": "text", "text": f"[{msg_type} 消息]: {raw_content}"})
  351. return blocks
  352. @tool(
  353. display={
  354. "zh": {
  355. "name": "获取飞书聊天历史记录",
  356. "params": {
  357. "contact_name": "联系人名称",
  358. "start_time": "起始时间戳 (秒),可选",
  359. "end_time": "结束时间戳 (秒),可选",
  360. "page_size": "分页大小,默认 20",
  361. "page_token": "分页令牌,用于加载下一页,可选"
  362. }
  363. },
  364. "en": {
  365. "name": "Get Feishu Chat History",
  366. "params": {
  367. "contact_name": "Contact Name",
  368. "start_time": "Start timestamp (seconds), optional",
  369. "end_time": "End timestamp (seconds), optional",
  370. "page_size": "Page size, default 20",
  371. "page_token": "Page token for next page, optional"
  372. }
  373. }
  374. }
  375. )
  376. async def feishu_get_chat_history(
  377. contact_name: str,
  378. start_time: Optional[int] = None,
  379. end_time: Optional[int] = None,
  380. page_size: int = 20,
  381. page_token: Optional[str] = None,
  382. context: Optional[ToolContext] = None
  383. ) -> ToolResult:
  384. """
  385. 根据联系人名称获取完整的历史聊天记录。
  386. 支持通过时间戳进行范围筛选,并支持分页获取。
  387. 返回的消息按时间倒序排列(最新的在前面)。
  388. Args:
  389. contact_name: 飞书联系人的名称
  390. start_time: 筛选起始时间的时间戳(秒),可选
  391. end_time: 筛选结束时间的时间戳(秒),可选
  392. page_size: 每页消息数量,默认为 20
  393. page_token: 分页令牌,用于加载上一页/下一页,可选
  394. context: 工具执行上下文(可选)
  395. """
  396. contact = get_contact_full_info(contact_name)
  397. if not contact:
  398. return ToolResult(title="获取历史失败", output=f"未找到联系人: {contact_name}", error="Contact not found")
  399. chat_id = contact.get("chat_id")
  400. if not chat_id:
  401. return ToolResult(title="获取历史失败", output=f"联系人 {contact_name} 尚未建立会话 (无 chat_id)", error="No chat_id")
  402. client = FeishuClient(app_id=FEISHU_APP_ID, app_secret=FEISHU_APP_SECRET)
  403. try:
  404. res = client.get_message_list(
  405. chat_id=chat_id,
  406. start_time=start_time,
  407. end_time=end_time,
  408. page_size=page_size,
  409. page_token=page_token
  410. )
  411. if not res or "items" not in res:
  412. return ToolResult(title="获取历史失败", output="请求接口失败或返回为空")
  413. # 将所有消息转换为 OpenAI 多模态格式
  414. formatted_messages = []
  415. for msg in res["items"]:
  416. formatted_messages.append({
  417. "message_id": msg.get("message_id"),
  418. "sender_id": msg.get("sender_id"),
  419. "sender_type": "assistant" if msg.get("sender_type") == "app" else "user",
  420. "create_time": msg.get("create_time"),
  421. "content": _convert_feishu_msg_to_openai_content(client, msg)
  422. })
  423. result_data = {
  424. "messages": formatted_messages,
  425. "page_token": res.get("page_token"),
  426. "has_more": res.get("has_more")
  427. }
  428. return ToolResult(
  429. title=f"获取 {contact_name} 历史记录成功",
  430. output=json.dumps(result_data, ensure_ascii=False, indent=2),
  431. metadata=result_data
  432. )
  433. except Exception as e:
  434. return ToolResult(title="获取历史异常", output=str(e), error=str(e))