search.py 8.1 KB

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