feishu_doc_tool.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. """Feishu Document Tool -- read document content via Feishu/Lark API.
  2. Provides ``feishu_doc_read`` for reading document content as plain text.
  3. Uses the same lazy-import + BaseRequest pattern as feishu_comment.py.
  4. """
  5. from tools.feishu_lark import (
  6. _check_feishu,
  7. build_request,
  8. get_client,
  9. raw_body,
  10. set_client)
  11. from tools.registry import registry, tool_error, tool_result
  12. _RAW_CONTENT_URI = "/open-apis/docx/v1/documents/:document_id/raw_content"
  13. FEISHU_DOC_READ_SCHEMA = {
  14. "name": "feishu_doc_read",
  15. "description": (
  16. "Read the full content of a Feishu/Lark document as plain text. "
  17. "Useful when you need more context beyond the quoted text in a comment."
  18. ),
  19. "parameters": {
  20. "type": "object",
  21. "properties": {
  22. "doc_token": {
  23. "type": "string",
  24. "description": "The document token (from the document URL or comment context).",
  25. },
  26. },
  27. "required": ["doc_token"],
  28. },
  29. }
  30. def _handle_feishu_doc_read(args: dict, **kwargs) -> str:
  31. doc_token = args.get("doc_token", "").strip()
  32. if not doc_token:
  33. return tool_error("doc_token is required")
  34. client = get_client()
  35. if client is None:
  36. return tool_error("Feishu client not available (not in a Feishu comment context)")
  37. try:
  38. request = build_request("GET", _RAW_CONTENT_URI, paths={"document_id": doc_token})
  39. except ImportError:
  40. return tool_error("lark_oapi not installed")
  41. # Handlers run synchronously in a worker thread (no event loop): call the blocking client.
  42. response = client.request(request)
  43. code = getattr(response, "code", None)
  44. if code != 0:
  45. return tool_error(f"Failed to read document: code={code} msg={getattr(response, 'msg', 'unknown error')}")
  46. body = raw_body(response)
  47. if body is not None:
  48. try:
  49. return tool_result(success=True, content=body.get("data", {}).get("content", ""))
  50. except AttributeError:
  51. pass
  52. data = getattr(response, "data", None) # fallback: the typed response.data
  53. if data:
  54. content = data.get("content", "") if isinstance(data, dict) else getattr(data, "content", str(data))
  55. return tool_result(success=True, content=content)
  56. return tool_error("No content returned from document API")
  57. registry.register(
  58. name="feishu_doc_read", toolset="feishu_doc", schema=FEISHU_DOC_READ_SCHEMA, handler=_handle_feishu_doc_read,
  59. check_fn=_check_feishu, requires_env=[], is_async=False, description="Read Feishu document content",
  60. emoji="\U0001f4c4")