chat.py 19 KB

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