douyin_search.py 2.6 KB

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