search.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. """
  2. 搜索工具模块
  3. 提供帖子搜索和建议词搜索功能,支持多个渠道平台。
  4. 主要功能:
  5. 1. search_posts - 帖子搜索
  6. 2. get_search_suggestions - 获取平台的搜索补全建议词
  7. """
  8. import json
  9. from enum import Enum
  10. from typing import Any, Dict
  11. import httpx
  12. from agent.tools import tool, ToolResult
  13. # API 基础配置
  14. BASE_URL = "http://aigc-channel.aiddit.com/aigc/channel"
  15. DEFAULT_TIMEOUT = 60.0
  16. class PostSearchChannel(str, Enum):
  17. """
  18. 帖子搜索支持的渠道类型
  19. """
  20. XHS = "xhs" # 小红书
  21. GZH = "gzh" # 公众号
  22. SPH = "sph" # 视频号
  23. GITHUB = "github" # GitHub
  24. TOUTIAO = "toutiao" # 头条
  25. DOUYIN = "douyin" # 抖音
  26. BILI = "bili" # B站
  27. ZHIHU = "zhihu" # 知乎
  28. WEIBO = "weibo" # 微博
  29. class SuggestSearchChannel(str, Enum):
  30. """
  31. 建议词搜索支持的渠道类型
  32. """
  33. XHS = "xhs" # 小红书
  34. WX = "wx" # 微信
  35. GITHUB = "github" # GitHub
  36. TOUTIAO = "toutiao" # 头条
  37. DOUYIN = "douyin" # 抖音
  38. BILI = "bili" # B站
  39. ZHIHU = "zhihu" # 知乎
  40. @tool(
  41. display={
  42. "zh": {
  43. "name": "帖子搜索",
  44. "params": {
  45. "keyword": "搜索关键词",
  46. "channel": "搜索渠道",
  47. "cursor": "分页游标",
  48. "max_count": "返回条数"
  49. }
  50. },
  51. "en": {
  52. "name": "Search Posts",
  53. "params": {
  54. "keyword": "Search keyword",
  55. "channel": "Search channel",
  56. "cursor": "Pagination cursor",
  57. "max_count": "Max results"
  58. }
  59. }
  60. }
  61. )
  62. async def search_posts(
  63. keyword: str,
  64. channel: str = "xhs",
  65. cursor: str = "0",
  66. max_count: int = 5,
  67. uid: str = "",
  68. ) -> ToolResult:
  69. """
  70. 帖子搜索
  71. 根据关键词在指定渠道平台搜索帖子内容。
  72. Args:
  73. keyword: 搜索关键词
  74. channel: 搜索渠道,支持的渠道有:
  75. - xhs: 小红书
  76. - gzh: 公众号
  77. - sph: 视频号
  78. - github: GitHub
  79. - toutiao: 头条
  80. - douyin: 抖音
  81. - bili: B站
  82. - zhihu: 知乎
  83. - weibo: 微博
  84. cursor: 分页游标,默认为 "0"(第一页)
  85. max_count: 返回的最大条数,默认为 5
  86. uid: 用户ID(自动注入)
  87. Returns:
  88. ToolResult 包含搜索结果:
  89. {
  90. "code": 0, # 状态码,0 表示成功
  91. "message": "success", # 状态消息
  92. "data": [ # 帖子列表
  93. {
  94. "channel_content_id": "68dd03db000000000303beb2", # 内容唯一ID
  95. "title": "", # 标题
  96. "content_type": "note", # 内容类型
  97. "body_text": "", # 正文内容
  98. "like_count": 127, # 点赞数
  99. "publish_timestamp": 1759314907000, # 发布时间戳(毫秒)
  100. "images": ["https://xxx.webp"], # 图片列表
  101. "videos": [], # 视频列表
  102. "channel": "xhs", # 来源渠道
  103. "link": "xxx" # 原文链接
  104. }
  105. ]
  106. }
  107. """
  108. try:
  109. # 处理 channel 参数,支持枚举和字符串
  110. channel_value = channel.value if isinstance(channel, PostSearchChannel) else channel
  111. url = f"{BASE_URL}/data"
  112. payload = {
  113. "type": channel_value,
  114. "keyword": keyword,
  115. "cursor": cursor,
  116. "max_count": max_count,
  117. }
  118. async with httpx.AsyncClient(timeout=DEFAULT_TIMEOUT) as client:
  119. response = await client.post(
  120. url,
  121. json=payload,
  122. headers={"Content-Type": "application/json"},
  123. )
  124. response.raise_for_status()
  125. data = response.json()
  126. # 计算结果数量
  127. result_count = len(data.get("data", []))
  128. return ToolResult(
  129. title=f"搜索结果: {keyword} ({channel_value})",
  130. output=json.dumps(data, ensure_ascii=False, indent=2),
  131. long_term_memory=f"Searched '{keyword}' on {channel_value}, found {result_count} posts"
  132. )
  133. except httpx.HTTPStatusError as e:
  134. return ToolResult(
  135. title="搜索失败",
  136. output="",
  137. error=f"HTTP error {e.response.status_code}: {e.response.text}"
  138. )
  139. except Exception as e:
  140. return ToolResult(
  141. title="搜索失败",
  142. output="",
  143. error=str(e)
  144. )
  145. @tool(
  146. display={
  147. "zh": {
  148. "name": "获取搜索关键词补全建议",
  149. "params": {
  150. "keyword": "搜索关键词",
  151. "channel": "搜索渠道"
  152. }
  153. },
  154. "en": {
  155. "name": "Get Search Suggestions",
  156. "params": {
  157. "keyword": "Search keyword",
  158. "channel": "Search channel"
  159. }
  160. }
  161. }
  162. )
  163. async def get_search_suggestions(
  164. keyword: str,
  165. channel: str = "xhs",
  166. uid: str = "",
  167. ) -> ToolResult:
  168. """
  169. 获取搜索关键词补全建议
  170. 根据关键词在指定渠道平台获取搜索建议词。
  171. Args:
  172. keyword: 搜索关键词
  173. channel: 搜索渠道,支持的渠道有:
  174. - xhs: 小红书
  175. - wx: 微信
  176. - github: GitHub
  177. - toutiao: 头条
  178. - douyin: 抖音
  179. - bili: B站
  180. - zhihu: 知乎
  181. uid: 用户ID(自动注入)
  182. Returns:
  183. ToolResult 包含建议词数据:
  184. {
  185. "code": 0, # 状态码,0 表示成功
  186. "message": "success", # 状态消息
  187. "data": [ # 建议词数据
  188. {
  189. "type": "xhs", # 渠道类型
  190. "list": [ # 建议词列表
  191. {
  192. "name": "彩虹染发" # 建议词
  193. }
  194. ]
  195. }
  196. ]
  197. }
  198. """
  199. try:
  200. # 处理 channel 参数,支持枚举和字符串
  201. channel_value = channel.value if isinstance(channel, SuggestSearchChannel) else channel
  202. url = f"{BASE_URL}/suggest"
  203. payload = {
  204. "type": channel_value,
  205. "keyword": keyword,
  206. }
  207. async with httpx.AsyncClient(timeout=DEFAULT_TIMEOUT) as client:
  208. response = await client.post(
  209. url,
  210. json=payload,
  211. headers={"Content-Type": "application/json"},
  212. )
  213. response.raise_for_status()
  214. data = response.json()
  215. # 计算建议词数量
  216. suggestion_count = 0
  217. for item in data.get("data", []):
  218. suggestion_count += len(item.get("list", []))
  219. return ToolResult(
  220. title=f"建议词: {keyword} ({channel_value})",
  221. output=json.dumps(data, ensure_ascii=False, indent=2),
  222. long_term_memory=f"Got {suggestion_count} suggestions for '{keyword}' on {channel_value}"
  223. )
  224. except httpx.HTTPStatusError as e:
  225. return ToolResult(
  226. title="获取建议词失败",
  227. output="",
  228. error=f"HTTP error {e.response.status_code}: {e.response.text}"
  229. )
  230. except Exception as e:
  231. return ToolResult(
  232. title="获取建议词失败",
  233. output="",
  234. error=str(e)
  235. )