# Harbor Agent SDK — Python `harbor_agent_sdk` (asyncio + `websockets`) — build a Harbor agent in Python. See [`../SPEC.md`](../SPEC.md) / [`../SPEC-highlevel.md`](../SPEC-highlevel.md). ```bash pip install harbor_agent_sdk--*.whl # the .whl from https://ai.nti56.com/dev/harbor/sdk// (pulls in `websockets`) ``` Install details: [`../README.md`](../README.md) (section 「获取与安装」). ## Quick start ```python from harbor_agent_sdk import Agent, Handler, Manifest, Dedup class EchoHandler(Handler): def __init__(self): self.dedup = Dedup() async def on_deliver_message(self, client, m): if not self.dedup.begin(m.contextId, m.changeSeq): # replay → ack & skip await client.ack_delivery(m.contextId, m.changeSeq); return await client.send_text(m.contextId, "echo: " + m.text, m.originatingPrincipal.id) await self.dedup.ack_processed(client, m.contextId, m.changeSeq) Agent(Manifest(displayName="小李", isMentionable=True), EchoHandler(), token="shared-secret", path="/agent").run(port=7501) ``` ## 成员生命周期 / 重连对账 `Handler` 另有两个回调(基类 no-op,旧 handler 不改即兼容): ```python class MyHandler(Handler): # #22:context 成员增量(join / leave / context-closed);在线直投、离线重连补投 async def on_context_lifecycle(self, client, e): if e.event == "context-closed": self.cache.drop_context(e.contextId) elif e.event == "participant-left": self.cache.drop_participant(e.contextId, e.participantId) elif e.event == "participant-joined" and e.isSelf: # 自身被加入 → 拉一次全员名册 await client.get_participants(e.contextId) # #23:(重)连接后下发当前在场 context 列表 → 对账,清理本地记着但不在列表的 async def on_resync(self, client, r): self.cache.reconcile_contexts([c.contextId for c in r.contexts]) ``` ## 回复语言:跟着这场对话说话(`replyLanguage`,SDK 0.51.0) 每条投递都带 `m.replyLanguage`(BCP-47,如 `"en-US"`;**`None` = 未锁定** ⇒ 用你自己的默认,别自己去检测) 与 `m.replyLanguageSource`(`REPLY_LANGUAGE_SOURCE_EXPLICIT` = 用户亲口选的、尤其要尊重; `REPLY_LANGUAGE_SOURCE_DETECTED` = Harbor 按前几条用户消息检测的,同样要跟随)。 🔴 **Harbor 的主模型就是按这一位回话的** —— 你不跟,用户看到的就是同一场对话里两种语言并排。 它是**对话级的锁**,不是「这条消息用什么语言写的」;Harbor 内部「仅此一轮」的临时切换不出现在这一位上。 ```python from harbor_agent_sdk import Handler, REPLY_LANGUAGE_SOURCE_EXPLICIT class MyHandler(Handler): def __init__(self, model_ref): self.model_ref = model_ref # 从 client.list_models() 里挑,别写死模型名 self.lang = {} # context_id → 当前语言锁 async def on_deliver_message(self, client, m): lang = m.replyLanguage or "zh-CN" # None ⇒ 回落到你自己的默认 system = f"Reply in {lang}." if m.replyLanguageSource == REPLY_LANGUAGE_SOURCE_EXPLICIT: system += " The user picked this language explicitly." r = await client.invoke_model_full( self.model_ref, [{"role": "user", "content": m.text}], 300, context_id=m.contextId, system=system, max_tokens=800) await client.send_text(m.contextId, r.text, m.originatingPrincipal.id) await client.ack_delivery(m.contextId, m.changeSeq) # 语言变更在线推 NotifyContextStyle(角色风格 + 回复语言的**全量快照**,不是 patch)⇒ 整体覆盖缓存 async def on_context_style(self, client, style): self.lang[style.contextId] = style.replyLanguage # None = 语言锁解开,回你自己的默认语言 # 离线期间的变更不排队 ⇒ 重连时以 resync 的快照为准对账 async def on_resync(self, client, r): for c in r.contexts: self.lang[c.contextId] = c.replyLanguage ``` 按需查同样有(这两个方法返回原始 dict):`(await client.get_participants(cid)).get("replyLanguage")`(未锁定时键干脆不出现); 跨对话行动前 `await client.list_my_contexts()` 每项也带 `replyLanguage` —— 别拿 A 对话的语言去回 B 对话。 不读这两个键的老 handler 行为逐字不变(只是仍会说错语言)。 ## 调模型:思考不是正文(SDK 0.51.0) 开了思维档的模型产出**思考**与**正文**两样东西,它们在同一次调用里回来。 ```python from harbor_agent_sdk import CHUNK_PHASE_REASONING # 非流式:text 只含正文,思考另走 thinking(None = 这次没思考) r = await client.invoke_model_full(model_ref, messages, 300, context_id=context_id, max_tokens=800) if r.finish == "incomplete": # 被 max_tokens 截断 —— 空的 / 半截的 text 是**合法返回**: return handle_truncated(r) # 🔴 不得当成功答案落库,按你的策略续写 / 重试 / 明说没答完 log.debug("thinking: %s", r.thinking) # 想看模型怎么想的读这里;常含被推翻的中间结论,别拼进答案 use(r.text) if r.usage: log.debug("reasoning tokens: %s", r.usage.reasoning) # 已含在 usage.output 内、不参与计费;本地路径是估算值 # 流式:聚合只收 phase != "reasoning" 的 delta;要思考就用 _full 变体 def on_chunk(chunk: dict) -> None: # 回调仍收到**每一格**,包括 reasoning if chunk.get("phase") == CHUNK_PHASE_REASONING: show_thinking(chunk.get("delta", "")) elif chunk.get("delta"): append_text(chunk["delta"]) # 缺省 / 认不出的 phase 按正文处理 if chunk.get("isFinal"): usage = chunk.get("usage") or {} log.debug("reasoning tokens: %s", usage.get("reasoning")) # 0.51.0 起流式终止帧也带 # 流式的截断判据同样是终止帧的 finish,不是「text 空不空」 if chunk.get("finish") == "incomplete": mark_truncated() text, thinking = await client.stream_invoke_model_full( model_ref, messages, 300, context_id=context_id, on_chunk=on_chunk) ``` - 只要正文就用 `await client.stream_invoke_model(...)`(= `stream_invoke_model_full(...)` 的第一项)。 - 🔴 **在 `on_chunk` 里自己拼字符串的必须自己按 `phase` 分流** —— 不分的后果不是「多点噪声」: 高思维档的思考链会逐字复述提示词里的 JSON 模板,按「首个完整 JSON」解析就会截到模板占位符。 ## 图像生成通道(SDK 0.55.0) `list_image_models()` / `generate_image(model_ref, body, context_id=None)` / `edit_image(model_ref, fields, images, mask=None, context_id=None)` —— gateway gpt-image 系的**纯透传**(2026-09-12,[skill §5.9](../../skills/harbor-agent-dev.skill.md))。 ```python from harbor_agent_sdk import ImagePart models = await client.list_image_models() # 先看 rates:medium 1024² ≈ 210 万计费量(r=200) r = await client.generate_image(models[0]["modelRef"], {"prompt": "一只红狐", "n": 1, "size": "1024x1024", "quality": "low", "output_format": "jpeg"}, context_id=ctx_id) # output_format 还可为 gif(+ frame_count / frame_duration_ms,只在 generations)或 svg(n=1)——取决于上游模型是否支持;响应的 output_format 以上游为准,先核再用。 png = base64.b64decode(r.b64_images[0]) # r.response = 上游 JSON 原样;r.usage.charged = 记进预算的量 e = await client.edit_image(models[0]["modelRef"], {"prompt": "换成海边背景", "input_fidelity": "high"}, [ImagePart.from_bytes("image/png", png, "in.png")], context_id=ctx_id) ``` - `body` 原样透传:**别放 `model`**(Harbor 也会删)、`stream: True` ⇒ `image_stream_not_supported`、`n` > 4(缺省)⇒ `invalid_args`;其余由上游 4xx 报 ⇒ `image_generation_failed`。 - 🔴 **Harbor 不存图**:b64 只在响应里,要给用户看就自己写文件区(`Files`)再发 `image` 块。 - 新错误字段:`HarborAgentError.upstream_status`(`int | None`)/ `upstream_error`(`dict | None`,上游 `{message,type,code,param}` 原样)/ `moderation_details`(`dict | None`);其余码恒 `None`。 - 🔴 **传输层改了一处**:`websockets` 收侧 `max_size` 缺省 1 MiB,一帧多张 b64 会 1009 断连 ⇒ `serve(max_size=WS_MAX_FRAME_BYTES)` 放到 64 MiB(`harbor_agent_sdk.transport.WS_MAX_FRAME_BYTES`)。 **跑图像通道的 Python agent 必须 ≥ 0.55.0**。 ## 工具失败带 `error_message`(SDK 0.54.0) `execute_tool` 回 `tool_invoke_timeout` / `agent_tool_timeout` 等工具失败时,Harbor 随码附一句模型面的话(哪件工具、等了多久、别假装执行过)。 `HarborAgentError.error_message`(`str | None`)承载它,与 `available_models` 同一条解码路径;`str(exc)` 文本不变(匹配靠 `code`,这句只是话术)。 ⚠️ **只有 Harbor 2026-09-12 之后的构建才发这个键**,老 Harbor 缺键 ⇒ `None` = 没给,不是「没有错误」。 ## High-level - `MessageBuilder().text("hi ").mention(id, "张三")` → `send_built(client, cid, b)`. - `client.set_status / clear_status` — progress badge. - `ToolpackHandler` — `h.register(ProvidedTool(...), fn)`; subclass for business; `h.manifest_tools()`. **SDK 0.53.0**:交给你的 `InvokeProvidedTool` 上挂着 Harbor 的响应窗口(默认 15s;帧带 `timeoutSec` 则按帧)—— `t.remaining()`(还剩几秒,直接喂 `asyncio.wait_for(coro, t.remaining())` / `async with asyncio.timeout(t.remaining())`)、 `t.deadline`(`time.monotonic()` 刻度)、`t.timeoutSec`。窗口一到 Harbor 就丢掉你的结果,别在它之后还继续算; 长任务仍走「秒回已受理 + 后台 `send_message`」。 **SDK 0.54.0**:Python 这里没变(没有连接级取消,`t.remaining()` 语义不变);本版是 Go 把窗口 ctx 挂到连接生命周期上(`conn.Context()`),与 C# 对齐。 - `ChoiceBroker` — `await broker.ask(...)`; call `broker.try_handle(m)` at top of `on_deliver_message`. Choice 失效规则(SDK 0.52.0:`selectMode` / `reentrant`)走 `ask(..., select_mode="single"|"multi", reentrant=False|True)` 的可选关键字参数 —— 既有调用逐字不变。Go 的拼法是新方法 `AskWith(..., ChoiceMode{SelectMode, Reentrant})`,C# 是 `AskAsync(..., selectMode:, reentrant:)`;三语言能力等价、只是形态不同。 ⚠️ `multi` 要等前端支持后才能用(在役前端见到 `selectMode != "single"` 会把整块静默丢掉)。 - `FileHandlerAgent(supported_mime_types, process, summarize)` — file-handler contract (§10). - `open_python_session/open_pg_session/open_file_session(client, context_id, ...)` — **Session** entity: hides the key, direct-connects to the component keyed port. `await s.exec(code)` / `s.install(*pkgs)` / `s.run_file(path)` (python), `s.pyenv_list/create/...` (preset mgmt), `s.query(sql, params, mode)` (pg); file bytes are **streaming-first**: `await s.open_read(relpath)` / `await s.open_write(relpath)` → async stream (juicefs-bytes plane, use `async with`), with `await s.download(relpath)` (read-side byte convenience, capped at `s.max_in_memory_bytes` default 8MB) / `await s.upload(relpath, data)` (write-side: **no size cap** — sends the caller-held bytes directly; use `open_write` for large files); `s.renew/revoke/close`, `s.expires_at`. - `Files(client, context_id)` — **unified file facade**: `list/delete/stat/move` (context area metadata, builtin `context.file.*`); file **content** is streaming-first over the harbor-agent WS Binary stream primitive (a `ContextFileRead`/`ContextFileWrite` control frame + Binary data frames on the same connection, no HTTP byte plane) — `await open_read(name)` / `await open_write(name, mime=None)` → async stream, with `await read(name)` / `await write(name, data)` as byte convenience wrappers; plus `fetch/mkdir/compress/extract/cross_copy/...` + `agent_tool(name,args)` (files-agent). See SPEC-highlevel §9. - `await open_user_view(client, context_id, title, url, proxy_agent_id="self", ...)` — ui.url.open. ### 大文件:优先流式,别整块 base64/bytes **读侧**便利包装 `Files.read` / `Session.download` 内部走流、结果攒进内存,上限 `max_in_memory_bytes`(默认 **8 MB**);超限抛 `HarborAgentError("file_too_large_use_stream")`,**不会静默截断**。**写侧**便利包装 `Files.write` / `Session.upload` **不校大小**——调用方已持有全量 bytes,直接流式发送、无此上限。大文件(尤其是写)请直接用流式 API: ```python files = Files(client, context_id) # context 区大文件:流式写(任意大小,不整体驻内存) async with await files.open_write("large.bin", mime="application/octet-stream") as w: with open("local-large.bin", "rb") as f: while chunk := f.read(65536): await w.write(chunk) # __aexit__ 正常退出 → close():flush + 等 PUT 完成,HTTP 失败在此处抛出 # context 区大文件:流式读(async for 逐块迭代) async with await files.open_read("large.bin") as r: async for chunk in r: process(chunk) # session 区(juicefs-bytes)同款:open_write/open_read session = await open_file_session(client, context_id) async with await session.open_read("some/relpath.bin") as r: async for chunk in r: process(chunk) ``` 调大 `files.max_in_memory_bytes` / `session.max_in_memory_bytes` 只是放宽**读侧**便利包装的上限;写侧便利本就无上限,流式路径本身也没有大小限制。 The `.whl` ships the library only (no example scripts). The Quick start above is a complete echo agent; fuller runnable examples (echo / file handler / context file streaming / permission gate) are in the `examples/` directory of the Go source package and serve as a reference — or ask the Harbor team for the Python `echo_agent.py` / `file_handler_agent.py` samples.