chat.py 19 KB

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