Metadata-Version: 2.5
Name: b3os-langchain
Version: 0.1.0
Summary: LangChain integrations for B3OS beta: a Deep Agents sandbox backend on a B3OS sandbox.
Project-URL: Documentation, https://docs.beta.b3os.org
Project-URL: Source, https://github.com/b3-fun/b3os-beta
Project-URL: Homepage, https://beta.b3os.org
License-Expression: Apache-2.0
License-File: LICENSE
Classifier: Programming Language :: Python :: 3
Classifier: Typing :: Typed
Requires-Python: >=3.11
Requires-Dist: b3os<0.3,>=0.2.1
Requires-Dist: deepagents<0.8,>=0.7.38
Provides-Extra: dev
Requires-Dist: mypy>=1.13; extra == 'dev'
Requires-Dist: pytest>=8; extra == 'dev'
Description-Content-Type: text/markdown

# b3os-langchain

LangChain integrations for B3OS beta. Today one: `B3OSSandbox`, a [Deep Agents](https://github.com/langchain-ai/deepagents)
sandbox backend, so a Deep Agent's shell and files live in a B3OS sandbox (a Firecracker microVM) while its model
can be served by the same node (`/v1/infer`).

```sh
pip install b3os-langchain langchain-openai
```

It brings the B3OS SDK (`b3os` 0.2.1 or later in 0.2) and `deepagents`. From a checkout of this repository:
`pip install ./packages/sdk-python ./packages/adapters-python/langchain`.

```python
import os

from b3os import B3OS
from deepagents import create_deep_agent
from langchain_b3os import B3OSSandbox
from langchain_openai import ChatOpenAI

sbx = B3OS().sandboxes.create({"template": "base"})          # B3OS_API_KEY from the environment
backend = B3OSSandbox(sandbox=sbx)
model = ChatOpenAI(model="b3os/qwen3.5-9b", base_url="https://beta-api.b3os.org/v1/infer", api_key=os.environ["B3OS_API_KEY"],
                   profile={"max_input_tokens": 32768})                        # context_length in /v1/infer/models
agent = create_deep_agent(model=model, system_prompt="You are a Python coding assistant with sandbox access.", backend=backend)
try:
    result = agent.invoke({"messages": [{"role": "user", "content": "Create a small Python package and run pytest"}]})
finally:
    sbx.kill()
```

## What it implements

`B3OSSandbox(sandbox=..., timeout=1800, user="root", cwd="/")` subclasses `deepagents.backends.sandbox.BaseSandbox` (read at
deepagents 0.7.38) and implements its four abstract members over the B3OS Python SDK's `Sandbox` handle:

| Member | B3OS call | Behaviour |
|---|---|---|
| `id` | `sbx.id` | The `sbx_...` id |
| `execute(command, timeout=None)` | `sbx.exec(["/bin/bash", "-c", command], cwd="/", timeout_ms=...)` | Runs in `/`, where Deep Agents roots a relative file path (`write_file("pkg/a.py")` is `/pkg/a.py`), so `mkdir pkg` and `cd pkg` reach the same files; `cwd="/workspace"` (B3OS's own default) for an agent told to work there. Output is stdout, then stderr on its own line. Up to 60 s it is one buffered call; longer (and the default 30 minutes) streams. `timeout=None` uses the backend's default, `0` and anything over an hour are held to B3OS's one-hour cap. A command killed at its timeout returns exit code 124 and `Command timed out after N seconds` before its partial output; one a signal ended returns 128 + n. `truncated` is true when B3OS dropped output (a buffered call returns at most 1 MiB of each stream) or a streamed command wrote more than 1 MiB to one stream (the SDK keeps the first 1 MiB as it arrives, `max_output_bytes`, and drops the rest) |
| `upload_files(files)` | `sbx.files.write(path, data, mkdir=True)` per file | Bytes as given (binary is fine); parent directories made |
| `download_files(paths)` | `sbx.files.read(path)` per path | Bytes as stored |

File errors are per file, in input order, never raised: a relative path (or one with a NUL byte or over 4,096
bytes) is `invalid_path` without a call; `file_not_found`, `is_directory`, `permission_denied` and `invalid_path`
map from the files API's answers; anything else is `"<code>: <detail>"`, for example
`file_too_large: ...` past the 64 MiB transfer cap. Absolute paths anywhere in the sandbox are allowed, as in the
partner backends: the sandbox is the boundary. Once the sandbox is gone (`sandbox_not_found`, `sandbox_not_running`)
the rest of a batch gets the same error without further calls, and `execute` raises the SDK's `B3OSError`.
When a command's answer is lost on the way rather than refused (`stream_interrupted` on a long stream, the SDK's
idle `timeout`, `connection_error`), `execute` does not raise, since Deep Agents' execute tool would end the whole
run: it returns no exit code and one JSON line, `{"error": "B3OS lost this command's answer (<code>: <detail>,
request req_...) ..."}`, which BaseSandbox's `ls`, `read`, `edit`, `grep` and `glob` read as a failure.

The other file tools (`ls`, `read`, `write`, `edit`, `delete`, `grep`, `glob`) are BaseSandbox's, built on
`execute` and `upload_files`; async methods are the protocol's thread-backed defaults, as in the Modal, Daytona and
Runloop backends. Capture-to-file offload of large output (`enable_capture_offload`) stays off, BaseSandbox's
default. The backend never creates or deletes a sandbox: you own its lifetime (`sbx.kill()`, `timeout_s` at create).

## Limits and B3OS gaps

- Commands run as root by default; B3OS's own default is `user` (uid 1000). Deep Agents
  writes its own files under `/` (`/large_tool_results/` when a tool result is too large, `/conversation_history/`
  when it summarizes), and BaseSandbox's `write` and `edit` make and change files through `execute`. As `user`
  those fail with `Permission denied` on `/`, while the files API, which writes as root, succeeds: the two halves
  of the sandbox act as different users. `user="user"` is there for agents that keep to `/workspace` and `/tmp`.
- Deep Agents summarizes a long conversation only when it knows the model's context size. LangChain has no
  profile for `b3os/qwen3.5-9b`, so pass it: `ChatOpenAI(..., profile={"max_input_tokens": 32768})`
  (`context_length` in `GET /v1/infer/models`). Without it a long run ends in `400 context_length_exceeded`.
- B3OS answers "is a directory" and "permission denied" as the same code, `path_invalid`; the backend tells them
  apart by the `detail` text.
- No single command runs longer than an hour (B3OS's streamed exec cap).
- Past 1 MiB of a stream nothing more is kept, so `yes` costs the agent's process 1 MiB, not an hour of output:
  the backend passes `max_output_bytes` to `Sandbox.exec`, and a broken stream's error carries its request id
  (both from b3os 0.2.1, the SDK floor).

## Development

```sh
cd packages/adapters-python/langchain
uv run --python 3.12 --locked --extra dev pytest -q      # the SDK's real handle over a fake API; no network
uv run --python 3.12 --locked --extra dev mypy --strict  # also on --python 3.11
```

The tests run on the SDK in this repository; `.github/workflows/release.yml` runs them again against the b3os wheel
it publishes beside this package. `uv.lock` is resolved with nothing newer than 2026-11-13 15:00 UTC
(`[tool.uv] exclude-newer`) and the SDK from `packages/sdk-python`.
The production proof (Deep Agents' own sandbox example on beta-api, model on `/v1/infer`) is in `proof/`, its
results in `bench/sandboxes/results/20261114T155056Z-deepagents-prod/`. The docs page is prepared in
`NOTES/integrations/langchain.mdx` until the package is published (`NOTES/integrations/README.md`).
