open-agent-docs 0.3.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- open_agent_docs-0.3.0/.gitignore +6 -0
- open_agent_docs-0.3.0/PKG-INFO +266 -0
- open_agent_docs-0.3.0/README.en.md +254 -0
- open_agent_docs-0.3.0/README.md +248 -0
- open_agent_docs-0.3.0/pyproject.toml +48 -0
- open_agent_docs-0.3.0/src/open_agent_docs/__init__.py +86 -0
- open_agent_docs-0.3.0/src/open_agent_docs/_base_client.py +667 -0
- open_agent_docs-0.3.0/src/open_agent_docs/_client.py +112 -0
- open_agent_docs-0.3.0/src/open_agent_docs/_embed.py +83 -0
- open_agent_docs-0.3.0/src/open_agent_docs/_errors.py +206 -0
- open_agent_docs-0.3.0/src/open_agent_docs/_files.py +51 -0
- open_agent_docs-0.3.0/src/open_agent_docs/_generated/__init__.py +2 -0
- open_agent_docs-0.3.0/src/open_agent_docs/_generated/models.py +1378 -0
- open_agent_docs-0.3.0/src/open_agent_docs/_generated/resources.py +4300 -0
- open_agent_docs-0.3.0/src/open_agent_docs/_models.py +17 -0
- open_agent_docs-0.3.0/src/open_agent_docs/_pagination.py +132 -0
- open_agent_docs-0.3.0/src/open_agent_docs/_server.py +330 -0
- open_agent_docs-0.3.0/src/open_agent_docs/_sse.py +335 -0
- open_agent_docs-0.3.0/src/open_agent_docs/_types.py +35 -0
- open_agent_docs-0.3.0/src/open_agent_docs/_utils.py +15 -0
- open_agent_docs-0.3.0/src/open_agent_docs/_version.py +1 -0
- open_agent_docs-0.3.0/src/open_agent_docs/_webhook.py +85 -0
- open_agent_docs-0.3.0/src/open_agent_docs/py.typed +0 -0
- open_agent_docs-0.3.0/src/open_agent_docs/types.py +3 -0
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: open-agent-docs
|
|
3
|
+
Version: 0.3.0
|
|
4
|
+
Summary: Open Agent Docs 的 Python SDK:同步 / 异步客户端、事件流、webhook 验签、JWT、本地起服务器
|
|
5
|
+
Project-URL: Homepage, https://github.com/kadaliao/open-agent-docs
|
|
6
|
+
Project-URL: Source, https://github.com/kadaliao/open-agent-docs/tree/main/sdks/python
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
Classifier: Framework :: AsyncIO
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
11
|
+
Classifier: Typing :: Typed
|
|
12
|
+
Requires-Python: >=3.9
|
|
13
|
+
Requires-Dist: httpx>=0.27
|
|
14
|
+
Requires-Dist: pydantic>=2
|
|
15
|
+
Provides-Extra: server
|
|
16
|
+
Requires-Dist: open-agent-docs-server==0.3.0; extra == 'server'
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
|
|
19
|
+
# open-agent-docs(Python SDK)
|
|
20
|
+
|
|
21
|
+
[English](README.en.md)
|
|
22
|
+
|
|
23
|
+
[Open Agent Docs](https://github.com/kadaliao/open-agent-docs) 的 Python 客户端:同步、异步两套一样的方法,模型是 pydantic v2,
|
|
24
|
+
带事件流、webhook 验签、签 JWT、嵌入地址和本地起服务器。依赖只有 `httpx` 和 `pydantic`,Python 3.9 起。
|
|
25
|
+
|
|
26
|
+
## 安装
|
|
27
|
+
|
|
28
|
+
```sh
|
|
29
|
+
pip install open-agent-docs
|
|
30
|
+
pip install "open-agent-docs[server]" # 再加上进程内的服务器(oad.start() 就不用下载二进制了)
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## 建客户端
|
|
34
|
+
|
|
35
|
+
```python
|
|
36
|
+
import open_agent_docs as oad
|
|
37
|
+
|
|
38
|
+
client = oad.Client(base_url="https://docs.example.com", token="oad_…")
|
|
39
|
+
client = oad.Client() # 读环境变量 OAD_BASE_URL(默认 http://127.0.0.1:8848)、OAD_TOKEN
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
`token` 可以是 Agent 的 token(`oad_…`)、登录后的会话令牌,或者 `OAD_AUTH=jwt` 时宿主签的 JWT。其它参数:
|
|
43
|
+
|
|
44
|
+
| 参数 | 默认 | 说明 |
|
|
45
|
+
| --- | --- | --- |
|
|
46
|
+
| `timeout` | 60 | 单个请求的超时(秒);事件流只管连接 |
|
|
47
|
+
| `max_retries` | 2 | 429、502/503/504、连不上时重试几次(POST、PATCH 遇到 5xx 不重试) |
|
|
48
|
+
| `locale` | 无 | `zh` / `en`:服务器错误信息的语言 |
|
|
49
|
+
| `headers` | 无 | 每个请求额外带的头 |
|
|
50
|
+
| `header_secret` / `jwt_secret` | 无 | 替用户调,见下面 |
|
|
51
|
+
| `jwt_issuer`、`jwt_audience`、`jwt_ttl` | 无、无、3600 | `with_user` 签 JWT 时写进去 |
|
|
52
|
+
| `http_client` | 无 | 自己的 `httpx.Client`(代理、证书之类) |
|
|
53
|
+
|
|
54
|
+
方法名和接口一一对应(点路径见 [sdks/operations.json](../operations.json)):`client.pages.versions.list(...)`、`client.me.get()`、`client.search(ws, q=...)`……
|
|
55
|
+
路径参数按顺序是位置参数,别的都是关键字参数。
|
|
56
|
+
|
|
57
|
+
## 建页面、写 Markdown
|
|
58
|
+
|
|
59
|
+
```python
|
|
60
|
+
ws = client.default_workspace() # /me 里的第一个工作区(每个客户端只取一次)
|
|
61
|
+
page = client.pages.create(ws, title="周报", markdown="# 本周\n\n- 上线了 Python SDK") # 建完再写正文,两步
|
|
62
|
+
|
|
63
|
+
content = client.pages.content.get(page.id) # content.markdown、content.version
|
|
64
|
+
client.pages.content.replace(page.id, markdown=content.markdown + "\n更多", base=content.version)
|
|
65
|
+
client.pages.update(page.id, title="第 47 周")
|
|
66
|
+
client.pages.update(page.id, after=None) # 明确发 null:放到最前
|
|
67
|
+
for p in client.pages.list(ws):
|
|
68
|
+
print(p.id, p.title)
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
可选参数不传就不发;要发 `null` 就传 `None`(`oad.NOT_GIVEN` 是“没给”)。
|
|
72
|
+
|
|
73
|
+
翻页的接口(`pages.versions.list`、`me.notifications.list`、`trash.list`……)返回一页 `oad.CursorPage`,直接 `for` 就会逐条取完所有页:
|
|
74
|
+
|
|
75
|
+
```python
|
|
76
|
+
page = client.pages.versions.list(page_id, limit=20)
|
|
77
|
+
page.items, page.next_cursor, page.has_next_page() # 这一页
|
|
78
|
+
for v in page: # 自动带 cursor 取后面的
|
|
79
|
+
print(v.id, v.label)
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
上传、下载:
|
|
83
|
+
|
|
84
|
+
```python
|
|
85
|
+
f = client.files.upload(ws, b"hello", "a.txt") # 也可以是 pathlib.Path、打开的文件、(文件名, bytes, 类型)
|
|
86
|
+
data = client.files.download(f.id) # bytes
|
|
87
|
+
db = client.databases.import_csv(ws, "名字,数量\n苹果,3\n", title="水果")
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
## 异步
|
|
91
|
+
|
|
92
|
+
```python
|
|
93
|
+
async with oad.AsyncClient() as client:
|
|
94
|
+
ws = await client.default_workspace()
|
|
95
|
+
page = await client.pages.create(ws, title="周报")
|
|
96
|
+
async for v in client.pages.versions.list(page.id): # 翻页:直接 async for(await 它拿第一页)
|
|
97
|
+
...
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
## 替用户调(宿主后端)
|
|
101
|
+
|
|
102
|
+
宿主自己做登录,后端以当前用户的身份调 Open Agent Docs。服务器配 `OAD_AUTH=header` + `OAD_HEADER_SECRET`,或者 `OAD_AUTH=jwt` + `OAD_JWT_SECRET`:
|
|
103
|
+
|
|
104
|
+
```python
|
|
105
|
+
admin = oad.Client(base_url=..., header_secret=SECRET) # 或 jwt_secret=SECRET
|
|
106
|
+
u = admin.with_user("u-42", name="王小明", email="x@example.com")
|
|
107
|
+
u.pages.list(u.default_workspace())
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
`with_user` 返回一个新的客户端(共享连接池和配置),原来的不变。header 模式带 `X-OAD-Secret`、`X-OAD-User-Id / -Name / -Email`;
|
|
111
|
+
JWT 模式签一个 HS256 的 JWT(缓存到过期前 60 秒),`workspaces=["ws1"]` 或 `[{"id": "ws1", "role": "viewer"}]` 写进 claims。
|
|
112
|
+
|
|
113
|
+
FastAPI 里:
|
|
114
|
+
|
|
115
|
+
```python
|
|
116
|
+
from fastapi import Depends, FastAPI, Request
|
|
117
|
+
import open_agent_docs as oad
|
|
118
|
+
|
|
119
|
+
app = FastAPI()
|
|
120
|
+
docs = oad.AsyncClient(base_url="http://127.0.0.1:8848", header_secret=SECRET) # 全局一个
|
|
121
|
+
|
|
122
|
+
async def docs_for(request: Request) -> oad.AsyncClient:
|
|
123
|
+
user = await my_current_user(request) # 宿主自己的登录
|
|
124
|
+
return docs.with_user(user.id, name=user.name, email=user.email)
|
|
125
|
+
|
|
126
|
+
@app.post("/notes")
|
|
127
|
+
async def create_note(title: str, text: str, d: oad.AsyncClient = Depends(docs_for)):
|
|
128
|
+
page = await d.pages.create(await d.default_workspace(), title=title, markdown=text)
|
|
129
|
+
return {"id": page.id}
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
完整的例子(进程内起服务器、两个用户):[examples/python-inprocess](../../examples/python-inprocess)。
|
|
133
|
+
|
|
134
|
+
## 嵌入:签 JWT、iframe 地址
|
|
135
|
+
|
|
136
|
+
```python
|
|
137
|
+
token = oad.sign_jwt(SECRET, "u-42", name="王小明", workspaces=["ws1"], ttl=3600) # HS256,只用标准库
|
|
138
|
+
url = oad.embed_url("https://docs.example.com", page_id, theme="dark", token=token)
|
|
139
|
+
# https://docs.example.com/p/<id>?embed=1&theme=dark#token=… (token 在 # 后面:不进服务器日志)
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
要 RS256 / ES256 的用自己的 JWT 库签,claims:`sub`、`name`、`email`、`workspaces`、`iat`、`exp`、`iss`、`aud`。
|
|
143
|
+
|
|
144
|
+
## 事件
|
|
145
|
+
|
|
146
|
+
```python
|
|
147
|
+
with client.workspaces.events(ws) as events: # 进 with 就连上了:之后发生的事件不会漏
|
|
148
|
+
for ev in events: # ev.name、ev.id、ev.data
|
|
149
|
+
if ev.name == "page.created":
|
|
150
|
+
print("新页面", ev.data.title) # data 按事件名解析成模型(Page……),不认识的给原始 JSON
|
|
151
|
+
elif ev.name == "resync":
|
|
152
|
+
... # 落下了:重新拉一遍
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
断了自动重连(1 秒起翻倍、最多 30 秒,带 `Last-Event-ID`);401、403、404 不重连,直接抛错。别的线程里 `events.close()` 能让它停下。
|
|
156
|
+
异步版:`async with client.workspaces.events(ws) as events: async for ev in events: ...`。
|
|
157
|
+
|
|
158
|
+
Agent 收通知(取 → 处理 → 确认):
|
|
159
|
+
|
|
160
|
+
```python
|
|
161
|
+
bot = oad.Client(token=AGENT_TOKEN)
|
|
162
|
+
with bot.agent.notifications.stream() as stream: # 先补发没确认的,再实时推;每条 data 是 AgentNotification
|
|
163
|
+
for ev in stream:
|
|
164
|
+
note = ev.data
|
|
165
|
+
reply = handle(note.prompt) # prompt 可以直接当消息发给你的 Agent
|
|
166
|
+
bot.threads.reply(note.thread_id, body=reply)
|
|
167
|
+
bot.agent.notifications.ack(ids=[note.id]) # 处理完再确认:断了重连会补发没确认的
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
不想开长连接就轮询:`bot.agent.notifications.list(wait=30)`(长轮询,返回一页)。
|
|
171
|
+
|
|
172
|
+
## Webhook
|
|
173
|
+
|
|
174
|
+
Agent 配了 webhook 地址时,服务器把通知 POST 过去,带 `X-OAD-Timestamp`、`X-OAD-Signature`。用建 Agent 时给的 `webhook_secret` 验:
|
|
175
|
+
|
|
176
|
+
```python
|
|
177
|
+
note = oad.verify_webhook(WEBHOOK_SECRET, headers, raw_body) # 返回 AgentNotification
|
|
178
|
+
# 不对抛 oad.WebhookVerificationError,e.kind 是 signature / stale / malformed;时间戳差超过 300 秒算 stale
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
一定用原始的正文字节(别解析了再序列化)。FastAPI:
|
|
182
|
+
|
|
183
|
+
```python
|
|
184
|
+
from fastapi import FastAPI, HTTPException, Request
|
|
185
|
+
|
|
186
|
+
@app.post("/oad-webhook")
|
|
187
|
+
async def webhook(request: Request):
|
|
188
|
+
try:
|
|
189
|
+
note = oad.verify_webhook(WEBHOOK_SECRET, request.headers, await request.body())
|
|
190
|
+
except oad.WebhookVerificationError as e:
|
|
191
|
+
raise HTTPException(401, e.kind)
|
|
192
|
+
background_tasks.add_task(handle, note) # 尽快回 2xx,慢活放后台
|
|
193
|
+
return {"ok": True}
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
Flask:
|
|
197
|
+
|
|
198
|
+
```python
|
|
199
|
+
from flask import Flask, abort, request
|
|
200
|
+
|
|
201
|
+
@app.post("/oad-webhook")
|
|
202
|
+
def webhook():
|
|
203
|
+
try:
|
|
204
|
+
note = oad.verify_webhook(WEBHOOK_SECRET, request.headers, request.get_data())
|
|
205
|
+
except oad.WebhookVerificationError:
|
|
206
|
+
abort(401)
|
|
207
|
+
queue.put(note)
|
|
208
|
+
return {"ok": True}
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
## 本地起服务器
|
|
212
|
+
|
|
213
|
+
```python
|
|
214
|
+
with oad.start(data_dir="./data", auth="header", header_secret=SECRET) as server:
|
|
215
|
+
client = oad.Client(base_url=server.url, header_secret=SECRET)
|
|
216
|
+
...
|
|
217
|
+
# 退出 with 时关掉(页面都存好再返回);或者 server = oad.start(...); ...; server.close()
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
- 关键字参数转成环境变量:`data_dir` → `OAD_DATA_DIR`、`auth` → `OAD_AUTH`……(和命令行一样,见 docs/zh/configuration.md);不给 `port` 挑一个空端口。
|
|
221
|
+
- 装了 `open-agent-docs[server]` 就在进程里跑(Rust,自己的线程,不占 GIL)。
|
|
222
|
+
- 没装就跑二进制:`binary=` → 环境变量 `OAD_BINARY` → 缓存(`~/Library/Caches/open-agent-docs/v<版本>/`、`~/.cache/open-agent-docs/v<版本>/`)→
|
|
223
|
+
从 GitHub 发布页下载(用同一个 release 的 `SHA256SUMS` 校验)。支持 macOS(arm64、x86_64)和 Linux(x86_64、aarch64),别的平台用 Docker。
|
|
224
|
+
|
|
225
|
+
## 错误
|
|
226
|
+
|
|
227
|
+
```python
|
|
228
|
+
try:
|
|
229
|
+
client.pages.get("nope")
|
|
230
|
+
except oad.NotFoundError as e:
|
|
231
|
+
print(e.status, e.code, e.message) # 404 not_found 页面 nope 不存在
|
|
232
|
+
except oad.RateLimitError as e:
|
|
233
|
+
time.sleep(e.retry_after or 1)
|
|
234
|
+
except oad.APIError as e: # 服务器回的别的错误:e.status、e.code、e.message、e.request_id
|
|
235
|
+
...
|
|
236
|
+
except oad.APIConnectionError: # 连不上(oad.APITimeoutError 是超时)
|
|
237
|
+
...
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
| 状态码 | 类 |
|
|
241
|
+
| --- | --- |
|
|
242
|
+
| 400 | `BadRequestError` |
|
|
243
|
+
| 401 | `AuthenticationError` |
|
|
244
|
+
| 403 | `PermissionDeniedError` |
|
|
245
|
+
| 404 | `NotFoundError` |
|
|
246
|
+
| 409 | `ConflictError`(比如 `base` 版本对不上) |
|
|
247
|
+
| 410 | `GoneError` |
|
|
248
|
+
| 413 | `TooLargeError` |
|
|
249
|
+
| 429 | `RateLimitError`(`retry_after`) |
|
|
250
|
+
| 502 | `BadGatewayError` |
|
|
251
|
+
| 其它 5xx | `InternalServerError`(`BadGatewayError` 是它的子类) |
|
|
252
|
+
|
|
253
|
+
所有错误的基类是 `oad.OADError`;配置不对是 `oad.ConfigurationError`。
|
|
254
|
+
|
|
255
|
+
## 开发
|
|
256
|
+
|
|
257
|
+
```sh
|
|
258
|
+
cd sdks/python
|
|
259
|
+
uv venv .venv && uv pip install --python .venv/bin/python -e . pytest pytest-asyncio pyright
|
|
260
|
+
python codegen/generate.py # 改了 docs/openapi.json 或 sdks/operations.json 后重新生成(src/open_agent_docs/_generated/)
|
|
261
|
+
python codegen/generate.py --check # 生成的是不是最新的(tests/test_codegen.py 也会查)
|
|
262
|
+
.venv/bin/python -m pytest # 单元测试;设了 OAD_BINARY 还跑场景测试(tests/conformance,S1–S15)
|
|
263
|
+
.venv/bin/pyright # 类型检查(strict)
|
|
264
|
+
```
|
|
265
|
+
|
|
266
|
+
模型和资源类是生成的(别手改),手写的运行时在 `src/open_agent_docs/_*.py`。
|
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
# open-agent-docs (Python SDK)
|
|
2
|
+
|
|
3
|
+
[中文](README.md)
|
|
4
|
+
|
|
5
|
+
The Python client for [Open Agent Docs](https://github.com/kadaliao/open-agent-docs): sync and async clients with the same methods,
|
|
6
|
+
pydantic v2 models, event streams, webhook verification, JWT signing, embed URLs and a local server launcher.
|
|
7
|
+
Dependencies: just `httpx` and `pydantic`. Python 3.9+.
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
```sh
|
|
12
|
+
pip install open-agent-docs
|
|
13
|
+
pip install "open-agent-docs[server]" # plus the in-process server (oad.start() won't need to download a binary)
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
## Create a client
|
|
17
|
+
|
|
18
|
+
```python
|
|
19
|
+
import open_agent_docs as oad
|
|
20
|
+
|
|
21
|
+
client = oad.Client(base_url="https://docs.example.com", token="oad_…")
|
|
22
|
+
client = oad.Client() # reads OAD_BASE_URL (default http://127.0.0.1:8848) and OAD_TOKEN
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
`token` can be an agent token (`oad_…`), a session token, or a JWT signed by the host when the server runs with `OAD_AUTH=jwt`. Other options:
|
|
26
|
+
|
|
27
|
+
| Option | Default | Meaning |
|
|
28
|
+
| --- | --- | --- |
|
|
29
|
+
| `timeout` | 60 | Per-request timeout in seconds; event streams only use it for connecting |
|
|
30
|
+
| `max_retries` | 2 | Retries on 429, 502/503/504 and connection failures (POST/PATCH aren't retried on 5xx) |
|
|
31
|
+
| `locale` | none | `zh` / `en`: language of server error messages |
|
|
32
|
+
| `headers` | none | Extra headers on every request |
|
|
33
|
+
| `header_secret` / `jwt_secret` | none | Calling on behalf of users, see below |
|
|
34
|
+
| `jwt_issuer`, `jwt_audience`, `jwt_ttl` | none, none, 3600 | Put into the JWT that `with_user` signs |
|
|
35
|
+
| `http_client` | none | Your own `httpx.Client` (proxies, certificates…) |
|
|
36
|
+
|
|
37
|
+
Method names map one-to-one to the API (see the dotted names in [sdks/operations.json](../operations.json)): `client.pages.versions.list(...)`,
|
|
38
|
+
`client.me.get()`, `client.search(ws, q=...)`… Path parameters are positional, everything else is keyword-only.
|
|
39
|
+
|
|
40
|
+
## Create a page and write Markdown
|
|
41
|
+
|
|
42
|
+
```python
|
|
43
|
+
ws = client.default_workspace() # first workspace in /me (fetched once per client)
|
|
44
|
+
page = client.pages.create(ws, title="Weekly", markdown="# This week\n\n- Shipped the Python SDK") # creates, then writes the body
|
|
45
|
+
|
|
46
|
+
content = client.pages.content.get(page.id) # content.markdown, content.version
|
|
47
|
+
client.pages.content.replace(page.id, markdown=content.markdown + "\nMore", base=content.version)
|
|
48
|
+
client.pages.update(page.id, title="Week 47")
|
|
49
|
+
client.pages.update(page.id, after=None) # explicitly send null: move to the top
|
|
50
|
+
for p in client.pages.list(ws):
|
|
51
|
+
print(p.id, p.title)
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Optional arguments you leave out aren't sent; pass `None` to send `null` (`oad.NOT_GIVEN` means "not given").
|
|
55
|
+
|
|
56
|
+
Paginated endpoints (`pages.versions.list`, `me.notifications.list`, `trash.list`…) return an `oad.CursorPage`; iterating it walks every page:
|
|
57
|
+
|
|
58
|
+
```python
|
|
59
|
+
page = client.pages.versions.list(page_id, limit=20)
|
|
60
|
+
page.items, page.next_cursor, page.has_next_page() # this page
|
|
61
|
+
for v in page: # follows the cursor automatically
|
|
62
|
+
print(v.id, v.label)
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
Uploads and downloads:
|
|
66
|
+
|
|
67
|
+
```python
|
|
68
|
+
f = client.files.upload(ws, b"hello", "a.txt") # also a pathlib.Path, an open file, or (name, bytes, type)
|
|
69
|
+
data = client.files.download(f.id) # bytes
|
|
70
|
+
db = client.databases.import_csv(ws, "name,qty\napple,3\n", title="Fruit")
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
## Async
|
|
74
|
+
|
|
75
|
+
```python
|
|
76
|
+
async with oad.AsyncClient() as client:
|
|
77
|
+
ws = await client.default_workspace()
|
|
78
|
+
page = await client.pages.create(ws, title="Weekly")
|
|
79
|
+
async for v in client.pages.versions.list(page.id): # pagination: async for directly (await it for one page)
|
|
80
|
+
...
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
## Calling on behalf of a user (host backends)
|
|
84
|
+
|
|
85
|
+
The host does its own login; its backend calls Open Agent Docs as the current user. Run the server with `OAD_AUTH=header` + `OAD_HEADER_SECRET`,
|
|
86
|
+
or `OAD_AUTH=jwt` + `OAD_JWT_SECRET`:
|
|
87
|
+
|
|
88
|
+
```python
|
|
89
|
+
admin = oad.Client(base_url=..., header_secret=SECRET) # or jwt_secret=SECRET
|
|
90
|
+
u = admin.with_user("u-42", name="Ming Wang", email="x@example.com")
|
|
91
|
+
u.pages.list(u.default_workspace())
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
`with_user` returns a new client (sharing the connection pool and settings); the original is unchanged. Header mode sends `X-OAD-Secret`
|
|
95
|
+
and `X-OAD-User-Id / -Name / -Email`; JWT mode signs an HS256 JWT (cached until 60 seconds before it expires), and `workspaces=["ws1"]`
|
|
96
|
+
or `[{"id": "ws1", "role": "viewer"}]` goes into the claims.
|
|
97
|
+
|
|
98
|
+
With FastAPI:
|
|
99
|
+
|
|
100
|
+
```python
|
|
101
|
+
from fastapi import Depends, FastAPI, Request
|
|
102
|
+
import open_agent_docs as oad
|
|
103
|
+
|
|
104
|
+
app = FastAPI()
|
|
105
|
+
docs = oad.AsyncClient(base_url="http://127.0.0.1:8848", header_secret=SECRET) # one for the whole app
|
|
106
|
+
|
|
107
|
+
async def docs_for(request: Request) -> oad.AsyncClient:
|
|
108
|
+
user = await my_current_user(request) # the host's own login
|
|
109
|
+
return docs.with_user(user.id, name=user.name, email=user.email)
|
|
110
|
+
|
|
111
|
+
@app.post("/notes")
|
|
112
|
+
async def create_note(title: str, text: str, d: oad.AsyncClient = Depends(docs_for)):
|
|
113
|
+
page = await d.pages.create(await d.default_workspace(), title=title, markdown=text)
|
|
114
|
+
return {"id": page.id}
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
Full example (in-process server, two users): [examples/python-inprocess](../../examples/python-inprocess).
|
|
118
|
+
|
|
119
|
+
## Embedding: sign a JWT, build the iframe URL
|
|
120
|
+
|
|
121
|
+
```python
|
|
122
|
+
token = oad.sign_jwt(SECRET, "u-42", name="Ming Wang", workspaces=["ws1"], ttl=3600) # HS256, standard library only
|
|
123
|
+
url = oad.embed_url("https://docs.example.com", page_id, theme="dark", token=token)
|
|
124
|
+
# https://docs.example.com/p/<id>?embed=1&theme=dark#token=… (the token is after #: it never reaches server logs)
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
For RS256 / ES256 use your own JWT library; claims: `sub`, `name`, `email`, `workspaces`, `iat`, `exp`, `iss`, `aud`.
|
|
128
|
+
|
|
129
|
+
## Events
|
|
130
|
+
|
|
131
|
+
```python
|
|
132
|
+
with client.workspaces.events(ws) as events: # connected once inside `with`: nothing after this is missed
|
|
133
|
+
for ev in events: # ev.name, ev.id, ev.data
|
|
134
|
+
if ev.name == "page.created":
|
|
135
|
+
print("new page", ev.data.title) # data is parsed by event name (Page…); unknown events give raw JSON
|
|
136
|
+
elif ev.name == "resync":
|
|
137
|
+
... # fell behind: reload
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
Reconnects automatically (1 s doubling up to 30 s, with `Last-Event-ID`); 401, 403 and 404 don't reconnect and raise.
|
|
141
|
+
`events.close()` from another thread stops it. Async: `async with client.workspaces.events(ws) as events: async for ev in events: ...`.
|
|
142
|
+
|
|
143
|
+
Agent notifications (fetch → handle → ack):
|
|
144
|
+
|
|
145
|
+
```python
|
|
146
|
+
bot = oad.Client(token=AGENT_TOKEN)
|
|
147
|
+
with bot.agent.notifications.stream() as stream: # replays unacked ones, then pushes live; each data is an AgentNotification
|
|
148
|
+
for ev in stream:
|
|
149
|
+
note = ev.data
|
|
150
|
+
reply = handle(note.prompt) # prompt can be sent to your agent as a message
|
|
151
|
+
bot.threads.reply(note.thread_id, body=reply)
|
|
152
|
+
bot.agent.notifications.ack(ids=[note.id]) # ack after handling: unacked ones are replayed on reconnect
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
Without a long-lived connection: `bot.agent.notifications.list(wait=30)` (long polling, returns one page).
|
|
156
|
+
|
|
157
|
+
## Webhooks
|
|
158
|
+
|
|
159
|
+
When an agent has a webhook URL, the server POSTs notifications to it with `X-OAD-Timestamp` and `X-OAD-Signature`. Verify with the
|
|
160
|
+
`webhook_secret` you got when creating the agent:
|
|
161
|
+
|
|
162
|
+
```python
|
|
163
|
+
note = oad.verify_webhook(WEBHOOK_SECRET, headers, raw_body) # returns an AgentNotification
|
|
164
|
+
# raises oad.WebhookVerificationError, e.kind is signature / stale / malformed; timestamps more than 300 s off are stale
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
Always pass the raw body bytes (don't parse and re-serialize). FastAPI:
|
|
168
|
+
|
|
169
|
+
```python
|
|
170
|
+
from fastapi import FastAPI, HTTPException, Request
|
|
171
|
+
|
|
172
|
+
@app.post("/oad-webhook")
|
|
173
|
+
async def webhook(request: Request):
|
|
174
|
+
try:
|
|
175
|
+
note = oad.verify_webhook(WEBHOOK_SECRET, request.headers, await request.body())
|
|
176
|
+
except oad.WebhookVerificationError as e:
|
|
177
|
+
raise HTTPException(401, e.kind)
|
|
178
|
+
background_tasks.add_task(handle, note) # answer 2xx quickly, do slow work in the background
|
|
179
|
+
return {"ok": True}
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
Flask:
|
|
183
|
+
|
|
184
|
+
```python
|
|
185
|
+
from flask import Flask, abort, request
|
|
186
|
+
|
|
187
|
+
@app.post("/oad-webhook")
|
|
188
|
+
def webhook():
|
|
189
|
+
try:
|
|
190
|
+
note = oad.verify_webhook(WEBHOOK_SECRET, request.headers, request.get_data())
|
|
191
|
+
except oad.WebhookVerificationError:
|
|
192
|
+
abort(401)
|
|
193
|
+
queue.put(note)
|
|
194
|
+
return {"ok": True}
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
## Run a server locally
|
|
198
|
+
|
|
199
|
+
```python
|
|
200
|
+
with oad.start(data_dir="./data", auth="header", header_secret=SECRET) as server:
|
|
201
|
+
client = oad.Client(base_url=server.url, header_secret=SECRET)
|
|
202
|
+
...
|
|
203
|
+
# stopped when leaving `with` (returns after pages are saved); or server = oad.start(...); ...; server.close()
|
|
204
|
+
```
|
|
205
|
+
|
|
206
|
+
- Keyword arguments become environment variables: `data_dir` → `OAD_DATA_DIR`, `auth` → `OAD_AUTH`… (same as the command line, see
|
|
207
|
+
docs/en/configuration.md); without `port` a free port is picked.
|
|
208
|
+
- With `open-agent-docs[server]` installed it runs inside the Python process (Rust, its own threads, doesn't hold the GIL).
|
|
209
|
+
- Otherwise it runs the binary: `binary=` → `OAD_BINARY` → cache (`~/Library/Caches/open-agent-docs/v<version>/`,
|
|
210
|
+
`~/.cache/open-agent-docs/v<version>/`) → download from the GitHub release (checked against that release's `SHA256SUMS`).
|
|
211
|
+
macOS (arm64, x86_64) and Linux (x86_64, aarch64) are supported; use Docker elsewhere.
|
|
212
|
+
|
|
213
|
+
## Errors
|
|
214
|
+
|
|
215
|
+
```python
|
|
216
|
+
try:
|
|
217
|
+
client.pages.get("nope")
|
|
218
|
+
except oad.NotFoundError as e:
|
|
219
|
+
print(e.status, e.code, e.message) # 404 not_found …
|
|
220
|
+
except oad.RateLimitError as e:
|
|
221
|
+
time.sleep(e.retry_after or 1)
|
|
222
|
+
except oad.APIError as e: # any other server error: e.status, e.code, e.message, e.request_id
|
|
223
|
+
...
|
|
224
|
+
except oad.APIConnectionError: # couldn't connect (oad.APITimeoutError for timeouts)
|
|
225
|
+
...
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
| Status | Class |
|
|
229
|
+
| --- | --- |
|
|
230
|
+
| 400 | `BadRequestError` |
|
|
231
|
+
| 401 | `AuthenticationError` |
|
|
232
|
+
| 403 | `PermissionDeniedError` |
|
|
233
|
+
| 404 | `NotFoundError` |
|
|
234
|
+
| 409 | `ConflictError` (e.g. a stale `base` version) |
|
|
235
|
+
| 410 | `GoneError` |
|
|
236
|
+
| 413 | `TooLargeError` |
|
|
237
|
+
| 429 | `RateLimitError` (`retry_after`) |
|
|
238
|
+
| 502 | `BadGatewayError` |
|
|
239
|
+
| other 5xx | `InternalServerError` (`BadGatewayError` is a subclass) |
|
|
240
|
+
|
|
241
|
+
Every error derives from `oad.OADError`; bad configuration raises `oad.ConfigurationError`.
|
|
242
|
+
|
|
243
|
+
## Development
|
|
244
|
+
|
|
245
|
+
```sh
|
|
246
|
+
cd sdks/python
|
|
247
|
+
uv venv .venv && uv pip install --python .venv/bin/python -e . pytest pytest-asyncio pyright
|
|
248
|
+
python codegen/generate.py # regenerate src/open_agent_docs/_generated/ after changing docs/openapi.json or sdks/operations.json
|
|
249
|
+
python codegen/generate.py --check # is the generated code up to date (tests/test_codegen.py checks too)
|
|
250
|
+
.venv/bin/python -m pytest # unit tests; with OAD_BINARY set also the scenario tests (tests/conformance, S1–S15)
|
|
251
|
+
.venv/bin/pyright # type check (strict)
|
|
252
|
+
```
|
|
253
|
+
|
|
254
|
+
Models and resource classes are generated (don't edit them by hand); the hand-written runtime lives in `src/open_agent_docs/_*.py`.
|