search.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  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. ) -> ToolResult:
  68. """
  69. 帖子搜索
  70. 根据关键词在指定渠道平台搜索帖子内容。
  71. Args:
  72. keyword: 搜索关键词
  73. channel: 搜索渠道,支持的渠道有:
  74. - xhs: 小红书
  75. - gzh: 公众号
  76. - sph: 视频号
  77. - github: GitHub
  78. - toutiao: 头条
  79. - douyin: 抖音
  80. - bili: B站
  81. - zhihu: 知乎
  82. - weibo: 微博
  83. cursor: 分页游标,默认为 "0"(第一页)
  84. max_count: 返回的最大条数,默认为 5
  85. Returns:
  86. ToolResult 包含搜索结果:
  87. {
  88. "code": 0, # 状态码,0 表示成功
  89. "message": "success", # 状态消息
  90. "data": [ # 帖子列表
  91. {
  92. "channel_content_id": "68dd03db000000000303beb2", # 内容唯一ID
  93. "title": "", # 标题
  94. "content_type": "note", # 内容类型
  95. "body_text": "", # 正文内容
  96. "like_count": 127, # 点赞数
  97. "publish_timestamp": 1759314907000, # 发布时间戳(毫秒)
  98. "images": ["https://xxx.webp"], # 图片列表
  99. "videos": [], # 视频列表
  100. "channel": "xhs", # 来源渠道
  101. "link": "xxx" # 原文链接
  102. }
  103. ]
  104. }
  105. """
  106. try:
  107. # 处理 channel 参数,支持枚举和字符串
  108. channel_value = channel.value if isinstance(channel, PostSearchChannel) else channel
  109. url = f"{BASE_URL}/data"
  110. payload = {
  111. "type": channel_value,
  112. "keyword": keyword,
  113. "cursor": cursor,
  114. "max_count": max_count,
  115. }
  116. async with httpx.AsyncClient(timeout=DEFAULT_TIMEOUT) as client:
  117. response = await client.post(
  118. url,
  119. json=payload,
  120. headers={"Content-Type": "application/json"},
  121. )
  122. response.raise_for_status()
  123. data = response.json()
  124. # 计算结果数量
  125. result_count = len(data.get("data", []))
  126. return ToolResult(
  127. title=f"搜索结果: {keyword} ({channel_value})",
  128. output=json.dumps(data, ensure_ascii=False, indent=2),
  129. long_term_memory=f"Searched '{keyword}' on {channel_value}, found {result_count} posts"
  130. )
  131. except httpx.HTTPStatusError as e:
  132. return ToolResult(
  133. title="搜索失败",
  134. output="",
  135. error=f"HTTP error {e.response.status_code}: {e.response.text}"
  136. )
  137. except Exception as e:
  138. return ToolResult(
  139. title="搜索失败",
  140. output="",
  141. error=str(e)
  142. )
  143. @tool(
  144. display={
  145. "zh": {
  146. "name": "获取搜索关键词补全建议",
  147. "params": {
  148. "keyword": "搜索关键词",
  149. "channel": "搜索渠道"
  150. }
  151. },
  152. "en": {
  153. "name": "Get Search Suggestions",
  154. "params": {
  155. "keyword": "Search keyword",
  156. "channel": "Search channel"
  157. }
  158. }
  159. }
  160. )
  161. async def get_search_suggestions(
  162. keyword: str,
  163. channel: str = "xhs",
  164. ) -> ToolResult:
  165. """
  166. 获取搜索关键词补全建议
  167. 根据关键词在指定渠道平台获取搜索建议词。
  168. Args:
  169. keyword: 搜索关键词
  170. channel: 搜索渠道,支持的渠道有:
  171. - xhs: 小红书
  172. - wx: 微信
  173. - github: GitHub
  174. - toutiao: 头条
  175. - douyin: 抖音
  176. - bili: B站
  177. - zhihu: 知乎
  178. Returns:
  179. ToolResult 包含建议词数据:
  180. {
  181. "code": 0, # 状态码,0 表示成功
  182. "message": "success", # 状态消息
  183. "data": [ # 建议词数据
  184. {
  185. "type": "xhs", # 渠道类型
  186. "list": [ # 建议词列表
  187. {
  188. "name": "彩虹染发" # 建议词
  189. }
  190. ]
  191. }
  192. ]
  193. }
  194. """
  195. try:
  196. # 处理 channel 参数,支持枚举和字符串
  197. channel_value = channel.value if isinstance(channel, SuggestSearchChannel) else channel
  198. url = f"{BASE_URL}/suggest"
  199. payload = {
  200. "type": channel_value,
  201. "keyword": keyword,
  202. }
  203. async with httpx.AsyncClient(timeout=DEFAULT_TIMEOUT) as client:
  204. response = await client.post(
  205. url,
  206. json=payload,
  207. headers={"Content-Type": "application/json"},
  208. )
  209. response.raise_for_status()
  210. data = response.json()
  211. # 计算建议词数量
  212. suggestion_count = 0
  213. for item in data.get("data", []):
  214. suggestion_count += len(item.get("list", []))
  215. return ToolResult(
  216. title=f"建议词: {keyword} ({channel_value})",
  217. output=json.dumps(data, ensure_ascii=False, indent=2),
  218. long_term_memory=f"Got {suggestion_count} suggestions for '{keyword}' on {channel_value}"
  219. )
  220. except httpx.HTTPStatusError as e:
  221. return ToolResult(
  222. title="获取建议词失败",
  223. output="",
  224. error=f"HTTP error {e.response.status_code}: {e.response.text}"
  225. )
  226. except Exception as e:
  227. return ToolResult(
  228. title="获取建议词失败",
  229. output="",
  230. error=str(e)
  231. )