context
feishu.agent.context
¶
工具的按轮上下文:让工具处理函数在不改变其参数签名的前提下访问飞书客户端与用户态客户端。
feishu.agent.loop.AgentEngine 在处理每条消息 / 卡片回调前,把一个 feishu.agent.context.ToolContext 设入一个
contextvars.ContextVar;工具处理函数(如 feishu.agent.toolkit 中的工厂所产出者)经
feishu.agent.context.current_tool_context 读取它。contextvars 的值会随 await 在同一任务内保持,并被
asyncio.to_thread(同步处理函数的执行方式)复制,因而读 / 写工具都能拿到正确的按轮上下文,而
feishu.agent.tools.ToolRegistry.dispatch 的签名保持不变。
ToolContext
dataclass
¶
一次工具调用的按轮上下文:租户客户端、触发事件、用户态 token 提供方与已解析的用户标识。
as_user 借助 user_tokens(feishu.auth 的用户态 token 提供方)解析「当前请求用户」的用户态飞书
客户端,用于需以用户身份执行的读写;缺少提供方或有效授权时返回 None,由工具自行决定降级或要求授权。
示例:
| Python Console Session | |
|---|---|
源代码位于: feishu/agent/context.py
| Python | |
|---|---|
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 | |
as_user
async
¶
as_user() -> Any | None
解析当前请求用户的用户态飞书客户端;无提供方 / 无授权时返回 None。
源代码位于: feishu/agent/context.py
has_user_auth
async
¶
判断当前请求用户是否已有有效授权;提供方支持 scope 检查时要求覆盖 scopes。
源代码位于: feishu/agent/context.py
requesting_user
¶
返回发起本轮请求的用户标识(open_id / union_id / user_id 的子集)。
优先使用显式传入的 user,否则从触发事件解析。用户主体类工具应据此把操作限定在「请求用户本人」,
防止被越权指向他人(zero-trust / least-privilege)。
源代码位于: feishu/agent/context.py
authorize_url
¶
为当前用户构造授权跳转 URL,供工具在缺少用户授权时回传给模型转述。
URL 的构造(重定向地址、state 签名等)由产品侧注入的 authorize_url_builder 负责,SDK 不内置任何
产品配置;未注入或无法解析用户时返回 None。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
|
Sequence[str]
|
本次操作所需的飞书权限范围。 |
()
|
返回:
| 类型 | 描述 |
|---|---|
str | None
|
授权 URL,或在未配置 / 无用户身份时返回 |
源代码位于: feishu/agent/context.py
current_timezone
async
¶
返回当前轮次的时区,优先使用飞书事件上下文,其次使用产品默认值。
源代码位于: feishu/agent/context.py
current_tool_context
¶
current_tool_context() -> ToolContext
读取当前生效的 feishu.agent.context.ToolContext;未设置时返回一个空上下文。
返回:
| 类型 | 描述 |
|---|---|
ToolContext
|
当前任务内由 feishu.agent.context.use_tool_context 设入的上下文;未设置时返回 |
ToolContext
|
( |
示例:
源代码位于: feishu/agent/context.py
use_tool_context
¶
use_tool_context(context: ToolContext) -> Iterator[None]
在 with 作用域内将 context 设为当前的 feishu.agent.context.ToolContext,退出时恢复。
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
|
ToolContext
|
本轮生效的工具上下文。 |
必需 |
示例:
| Python Console Session | |
|---|---|