douyin_search.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. """
  2. 抖音关键词搜索工具(示例)
  3. 调用内部爬虫服务进行抖音关键词搜索。
  4. """
  5. import asyncio
  6. import json
  7. from typing import Optional
  8. import httpx
  9. from agent.tools import tool, ToolResult
  10. # API 基础配置
  11. DOUYIN_SEARCH_API = "http://crawapi.piaoquantv.com/crawler/dou_yin/keyword"
  12. DEFAULT_TIMEOUT = 60.0
  13. @tool(description="通过关键词搜索抖音视频内容")
  14. async def douyin_search(
  15. keyword: str,
  16. content_type: str = "视频",
  17. sort_type: str = "综合排序",
  18. publish_time: str = "不限",
  19. cursor: str = "0",
  20. account_id: str = "",
  21. timeout: Optional[float] = None,
  22. ) -> ToolResult:
  23. """
  24. 抖音关键词搜索
  25. Args:
  26. keyword: 搜索关键词
  27. content_type: 内容类型(默认 "视频")
  28. sort_type: 排序方式(默认 "综合排序")
  29. publish_time: 发布时间范围(默认 "不限")
  30. cursor: 分页游标(默认 "0")
  31. account_id: 账号ID(可选)
  32. timeout: 超时时间(秒),默认 60
  33. Returns:
  34. ToolResult: 搜索结果 JSON
  35. """
  36. try:
  37. payload = {
  38. "keyword": keyword,
  39. "content_type": content_type,
  40. "sort_type": sort_type,
  41. "publish_time": publish_time,
  42. "cursor": cursor,
  43. "account_id": account_id
  44. }
  45. request_timeout = timeout if timeout is not None else DEFAULT_TIMEOUT
  46. async with httpx.AsyncClient(timeout=request_timeout) as client:
  47. response = await client.post(
  48. DOUYIN_SEARCH_API,
  49. json=payload,
  50. headers={"Content-Type": "application/json"},
  51. )
  52. response.raise_for_status()
  53. data = response.json()
  54. return ToolResult(
  55. title=f"抖音搜索: {keyword}",
  56. output=json.dumps(data, ensure_ascii=False, indent=2),
  57. long_term_memory=f"Searched Douyin for '{keyword}'"
  58. )
  59. except httpx.HTTPStatusError as e:
  60. return ToolResult(
  61. title="抖音搜索失败",
  62. output="",
  63. error=f"HTTP error {e.response.status_code}: {e.response.text}"
  64. )
  65. except Exception as e:
  66. return ToolResult(
  67. title="抖音搜索失败",
  68. output="",
  69. error=str(e)
  70. )
  71. #
  72. # async def main():
  73. # result = await douyin_search(
  74. # keyword="宁艺卓",
  75. # account_id = "771431186"
  76. # )
  77. # print(result.output)
  78. #
  79. # if __name__ == "__main__":
  80. # asyncio.run(main())