Use nanobot as a Python library. The SDK gives you the same agent runtime used by the CLI, but from code: model routing, tools, workspace access, conversation history, memory, streaming events, and runtime helpers.
Install and configure nanobot first. If you have not done that yet, follow the [Quick Start](quick-start.md) and complete the setup wizard. For SDK-only Python environments, install the package with:
`Nanobot.from_config()` reuses your normal `~/.nanobot/config.json` and `~/.nanobot/workspace/`. Provider, model, tools, memory, and session behavior match the CLI unless you override them. For the difference between config and workspace, see [Concepts: Config vs Workspace](concepts.md#config-vs-workspace).
If you have already received a normal reply in the WebUI, use that saved configuration directly. For a separate Python environment, `nanobot status` shows which config, workspace, and model the SDK will load.
Use `async with` when possible so tool connections and background cleanup are closed before the event loop exits. If you manage the instance manually, call `await bot.aclose()` in a `finally` block.
The SDK is async-first because agent runs may stream tokens, execute tools, and wait on external services. In a normal Python script, wrap your async function with `asyncio.run(...)` as shown above. In a notebook or another async app, call `await bot.run(...)` directly from your existing event loop.
The default agent workspace comes from config, not the notebook's current directory. For a notebook that should use its current folder as both file workspace and agent state, choose it explicitly:
result=awaitbot.run("List the files in this workspace.")
```
This also places memory and skills in that workspace. Use a separate configured instance when notebook experiments must not share existing agent state.
This gives each task or workflow its own conversation thread. Keys do not isolate workspace files, tools, credentials, or long-term memory: sessions in one agent workspace share `USER.md`, `SOUL.md`, and `memory/MEMORY.md`. For separate users or tenants, use separate configured instances and appropriate process/file permissions; see [Multiple Instances](multiple-instances.md).
You should see the configured model, workspace path, streamed assistant text, and final run metadata. The exact answer depends on your config and workspace, but a file-listing prompt may look like this:
This script shows the usual production shape: create one `Nanobot`, choose a stable `session_key`, stream events, keep the final `RunResult`, and let `async with` close runtime resources.
| `Nanobot` | The SDK object that owns one configured agent runtime. |
| Run | One call to `bot.run(...)`, `bot.run_streamed(...)`, or `bot.stream(...)`. |
| `session_key` | The conversation history key. Reuse it to continue a thread; change it to isolate a thread. |
| Workspace | The local directory where file tools and shell tools operate. |
| Tools | Capabilities the agent may call, such as file access, shell, web, or custom tools from your config. |
| Memory | Long-term memory files managed by nanobot. |
| Stream event | A typed event such as `text.delta`, `tool.started`, or `run.completed`. |
| Model override | A temporary model or model preset used for one SDK instance or one run. |
For most users, the mental model is:
1. Create a `Nanobot` from config.
2. Pick a `session_key`.
3. Call `run` or `stream`.
4. Read `RunResult` or stream events.
5. Use session/memory/runtime helpers only when you need more control.
## SDK Or OpenAI-Compatible API?
nanobot has two programming surfaces:
| Use | Choose | Why |
|-----|--------|-----|
| Python code running in the same process as nanobot | Python SDK | Direct access to `RunResult`, sessions, memory, runtime helpers, hooks, and stream events. |
| Existing OpenAI-compatible clients, another language, or a separate process | [OpenAI-Compatible API](openai-api.md) | HTTP `/v1/chat/completions` compatibility with familiar client libraries. |
The Python SDK is best when you are writing evals, notebooks, benchmark runners, product backends, local scripts, or integrations that should control nanobot directly.
The config controls what nanobot may use. The workspace is where nanobot keeps state for that instance. See [multiple-instances.md](multiple-instances.md) for multi-instance CLI and gateway examples.
For first setup, create named presets in **Settings → Models**; the SDK reads those saved presets from `config.json`. Mixing an API key from one provider with a model ID from another is the most common first-run failure. For the exact difference between `provider`, `model`, `apiKey`, and `apiBase`, see [Providers: Provider, Model, API Key, and Base URL](providers.md#provider-model-api-key-and-base-url). If a run fails before the SDK does anything interesting, confirm the same provider and model work with `nanobot agent -m "Hello!"` first.
Avoid using the default `"sdk:default"` for multiple users or unrelated workflows. It is convenient for local experiments, but stable product code should choose explicit keys such as `user:<id>`, `project:<id>`, or `eval:<case-id>`.
Always either consume the stream, call `await run.wait()` / `await run.text()`, or close it with `await run.cancel()` / `await run.aclose()`. Exiting `stream_events()` or `bot.stream()` early cancels the underlying run so a half-consumed stream cannot leave a background task stuck behind backpressure.
Use `bot.sessions.ingest()` when you already have a transcript and want it to become nanobot session history. Ingesting a transcript does not call the model, execute tools, update memory, or compact automatically.
Saved session history and curated long-term memory are different. The SDK does not start the gateway scheduler, so creating or closing `Nanobot` does not schedule Dream. Compaction archives a conversation into `memory/history.jsonl`; it does not itself update `USER.md` or `memory/MEMORY.md`.
Before closing a script that should contribute material to Dream:
```python
asyncwithNanobot.from_config()asbot:
awaitbot.run("For release notes, use concise bullet points.",session_key="sdk:notes")
Then use `/dream` in a running WebUI or TUI connected to the same configured agent workspace, wait for completion, and inspect `/dream-log`. Scheduled Dream also processes this archive while the matching gateway runs and Dream is enabled. `await bot.run("/dream")` only returns the command acknowledgement; it is not an awaited Dream-completion API for short-lived scripts.
For application-owned durable text, `bot.memory.write(text)` writes `memory/MEMORY.md` directly and `bot.memory.read()` reads it back. Writing replaces the whole file; it does not merge preferences or create a Dream audit entry. See [Memory](memory.md) for review and correction workflows.
Hooks are an advanced escape hatch. Use them when you want custom logging, metrics, tracing, or output post-processing without modifying nanobot internals:
| `attributes` | `Mapping[str, Any] \| None` | `None` | Caller-owned request data for host integrations. It is available to context providers and turn-hook factories, but is not added to trusted message metadata or persisted in session messages. |
Without an override, a run uses the preset saved in its session, or the configured default when that session has no saved selection. `model` and `model_preset` are mutually exclusive per-run overrides; they do not change the saved session selection or `bot.runtime.model` after the run completes.
SDK runs with different session keys may overlap, including runs with per-run `model` or `model_preset` overrides. Each run receives an immutable runtime without mutating the instance default. Runs sharing one session key remain serialized.
| `await export(session_key)` | Return a trusted full `SessionSnapshot`, including model-only runtime context, suitable for JSON serialization. |
| `await restore(snapshot, session_key=None)` | Restore a trusted exported snapshot into an empty session; the returned snapshot is display-safe. |
| `await clear(session_key)` | Clear and persist one session. |
| `await delete(session_key)` | Delete one session from disk and cache. |
Session writes commit before returning. Returned snapshots are detached; changing a snapshot does not save it. See [Session storage](cli-reference.md#session-storage) for upgrade and backup instructions.
Ingested messages must include `role` and `content`. Roles may be `user`, `assistant`, `tool`, or `system`. Other fields, such as `timestamp`, `source_session_id`, or `source_date`, are persisted as message metadata.
`get()` and snapshots returned by ordinary SDK operations are display-safe and omit model-only runtime context. `export()` is an explicit backup boundary and includes that internal context so `restore()` can preserve the exact model-visible history. Do not expose exported snapshots directly to chat users.
| `on_session_turn_persisted(handler)` | Register a best-effort sync or async callback for locally persisted turns and return an unsubscribe callback. |
Both compaction methods serialize with turns for the same session key. Call them after `bot.run()` returns, or from a separate task that can wait for the active turn to finish.
Host applications can attach external context without copying or modifying the nanobot agent loop. A context provider receives a `RequestContext` before each model turn and may return one or more `RuntimeContextBlock` values. Use `attributes` for caller-owned routing data; nanobot keeps it separate from trusted channel metadata and does not persist it in session messages.
`on_session_turn_persisted()` invokes its callback after a non-ephemeral turn has been saved. The callback receives `SessionTurnPersisted` and may read the completed transcript through `bot.sessions`. Callbacks run in registration order, and async callbacks are awaited before the run continues. They are observational: callback exceptions are logged and suppressed so the completed local turn remains successful. Durable external synchronization must catch failures and persist retry work before the callback returns. During SDK runs, callbacks execute while the session is still serialized. Schedule `bot.run()`, `bot.runtime.compact_session()`, or `bot.runtime.compact_idle_session()` for the same session after the callback returns.
Context providers are trusted host extensions, and `RuntimeContextBlock.content` is appended verbatim to model-visible context. Apply equivalent bounding, encoding, and delimiter escaping to untrusted external content. Persisted-turn callbacks are not invoked for `ephemeral=True` runs.