---
title: Integrate Langfuse with Strands Box
sidebarTitle: Strands Box
logo: /images/integrations/strands-box_icon.svg
description: Trace Strands agents running inside Strands Box with Langfuse via OpenTelemetry, locally or on Amazon Bedrock AgentCore Runtime.
---

# Integrate Langfuse with Strands Box

This guide shows you how to trace a Strands agent running inside **Strands Box** with **Langfuse**. You can inspect its model calls, tool calls, answers and token usage while Box keeps the Langfuse credential outside the agent process.

> **What is Strands Box?** [Strands Box](https://strandsagents.com/docs/user-guide/box/) runs an agent in a contained process with declared file, network and credential access.

> **What is Langfuse?** [Langfuse](https://langfuse.com) is an open-source AI engineering platform. It provides tracing, debugging, evaluation, and monitoring capabilities for AI agents and LLM applications. Use [Langfuse Cloud](/cloud) (hosted by Langfuse, free tier, no infrastructure to run) or [self-host](/self-hosting) it.

[Strands Agents](/integrations/frameworks/strands-agents) records the agent's work as OpenTelemetry traces. Box forwards those traces to Langfuse with your project's API keys.

  ![A Strands README agent in Langfuse, showing its native invocation, two model calls and a file-reading tool](/images/cookbook/integration-strands-box/box-readme-agent-trace.png)

**Start with Langfuse** [Sign up](/cloud)

## Setup steps [#setup]

In this tutorial, we will use the [Box Python agent setup](https://strandsagents.com/docs/user-guide/box/guides/run-strands-harness/) and use its `~/box-tutorial` folder. The steps below add tracing.

<Steps>

### Add tracing to the agent

Install tracing support in the agent's Python environment:

```bash
cd ~/box-tutorial
strands-agent/runtime/.venv/bin/python3 -m pip install -U "strands-agents[otel]"
```

Replace `strands-agent/agent.py` with this agent, which has one tool, `read_readme`:

```python filename="agent.py"
"""A native Strands README agent, launched by Box."""
import os
from pathlib import Path
import sys

from strands import Agent, tool
from strands.models import BedrockModel
from strands.telemetry import StrandsTelemetry


@tool
def read_readme() -> str:
    """Read README.md from the agent's workspace."""
    return Path("README.md").read_text()


telemetry = StrandsTelemetry().setup_otlp_exporter(timeout=5)
agent = Agent(
    name="readme-assistant",
    model=BedrockModel(
        model_id=os.environ["MODEL_ID"],
        region_name=os.environ["AWS_REGION"],
        max_tokens=256,
    ),
    tools=[read_readme],
    system_prompt="Use read_readme to answer questions about README.md. Reply briefly.",
    callback_handler=None,
)
try:
    result = agent(" ".join(sys.argv[1:]))
    print(str(result))
finally:
    if not telemetry.tracer_provider.force_flush(timeout_millis=10000):
        raise RuntimeError("The trace exporter did not flush")
    telemetry.tracer_provider.shutdown()
```

Two parts of this file are for tracing: `StrandsTelemetry().setup_otlp_exporter()` turns on trace export, and the `finally` block sends the trace before the process exits. Add the same two parts to trace your own agent.

### Set the Langfuse API keys

Get a public and a secret key from [API keys](https://cloud.langfuse.com/project/~/settings/api-keys). Set them as one `public-key:secret-key` value in the operator environment, which is the shell that launches Box:

```bash
export LANGFUSE_AUTH="pk-lf-...:sk-lf-..."
```

### Configure Box export

Add these values to the agent's existing environment in `box.toml`:

```toml filename="box.toml"
[agent.env]
OTEL_TRACES_EXPORTER = "otlp"
OTEL_SERVICE_NAME = "box-readme-agent"
OTEL_SEMCONV_STABILITY_OPT_IN = "gen_ai_latest_experimental,gen_ai_span_attributes_only"
```

The Box setup guide's `box.toml` defines the environment as an inline `env = { ... }` table under `[agent]`. In that case, add the three values inside that table instead, and keep its existing model and runtime settings.

`OTEL_SEMCONV_STABILITY_OPT_IN` makes Strands record model inputs and outputs as structured messages, including tool calls and tool results. Without it, Langfuse receives the same messages as JSON-encoded strings.

Add a Langfuse telemetry target:

```toml filename="box.toml"
[telemetry.langfuse]
kind = "langfuse"
destination = "https://cloud.langfuse.com" # 🇪🇺 EU region
# Other Langfuse data regions include 🇺🇸 US: https://us.cloud.langfuse.com, 🇯🇵 Japan: https://jp.cloud.langfuse.com and ⚕️ HIPAA: https://hipaa.cloud.langfuse.com
secret.ref = "env://LANGFUSE_AUTH"
include = ["trace"]
```

Box resolves the keys from the operator environment and sends the agent's traces to Langfuse itself.

  The `langfuse` target requires Box v0.2.4 or later. Keep Langfuse keys and
  `OTEL_EXPORTER_OTLP_*` settings out of `[agent.env]`. Box sets the contained
  agent's OTLP endpoint to its own loopback receiver. Adding a telemetry target
  replaces Box's default local file target; retain an explicit file target if
  you need local policy and lifecycle records, as described in [Box
  telemetry](https://strandsagents.com/docs/user-guide/box/guides/record-telemetry/).

<Details>
<Summary>Use Box's generic OTLP target instead</Summary>

The `langfuse` target is a preset of Box's generic `otlp` target. To set the endpoint path, headers, and authentication yourself, replace it with the equivalent `otlp` target:

```toml filename="box.toml"
[telemetry.langfuse]
kind = "otlp"
destination = "https://cloud.langfuse.com/api/public/otel" # 🇪🇺 EU region
# Other Langfuse data regions include 🇺🇸 US: https://us.cloud.langfuse.com, 🇯🇵 Japan: https://jp.cloud.langfuse.com and ⚕️ HIPAA: https://hipaa.cloud.langfuse.com
secret.ref = "env://LANGFUSE_AUTH"
secret.placement = "basic_auth"
headers = { "x-langfuse-ingestion-version" = "4" }
include = ["trace"]
accepts = ["traces"]
```

Keep `accepts = ["traces"]`. Without it, Box also sends logs, which Langfuse does not ingest, and warns that telemetry records were lost. The header enables [real-time ingestion](/integrations/native/opentelemetry#real-time-ingestion).

</Details>

### Run the task

Put these lines in `~/box-tutorial/my-project/README.md`:

```text filename="README.md"
Project Atlas
Owner: Maya
Release day: Tuesday
```

In `strands-agent/box.toml`, add `"~/box-tutorial/my-project/README.md"` to the `read_file` list under `[agent.filesystem]`, so the agent can read the file.

Run Box in the shell that holds `LANGFUSE_AUTH` and your model credential:

```bash
cd ~/box-tutorial
./box-core/box run --config strands-agent/box.toml -- "Who owns Project Atlas, and when is the release?"
```

The answer names **Maya** and **Tuesday**.

### View the trace

Open [Tracing](https://cloud.langfuse.com/project/~/traces) in your Langfuse project and find the new `invoke_agent readme-assistant` observation. Expect two `chat` model calls and one `read_readme` tool call, with the model input, tool result, answer and token usage.

Box also sends its own lifecycle spans, such as `control box_started`, as a [separate trace](#box-lifecycle-traces).

</Steps>

## Run on AgentCore Runtime [#agentcore]

This section is optional. Box runs wherever you start it: on your machine, as in the steps above, or in a cloud environment. [Amazon Bedrock AgentCore Runtime](/integrations/frameworks/amazon-agentcore) is one such environment; the [Box documentation](https://strandsagents.com/docs/user-guide/box/) covers others.

On AgentCore Runtime, the agent and the Langfuse settings stay the same. Three things change: `box.toml` uses the Runtime's Linux paths, an entrypoint starts Box for each request, and `LANGFUSE_AUTH` becomes a Runtime environment variable.

The example is a direct code deployment on the Runtime's Python 3.13 environment, which unpacks the package to `/var/task`.

<Steps>

### Configure Box for the Runtime

Create a `box.toml` for the package. It has the same `OTEL_*` values and `[telemetry.langfuse]` target as the local setup; the paths and filesystem grants are the Runtime's.

<Details>
<Summary>Complete box.toml for AgentCore Runtime</Summary>

```toml filename="box.toml"
name = "readme-agent"
box_dir = "/var/tmp/box-readme/state"
policy = "policy.dw"

[agent]
command = ["/usr/bin/python3.13", "/var/task/agent.py"]
workspace = "/var/task/workspace"

[agent.env]
AWS_REGION = "us-west-2"
AWS_EC2_METADATA_DISABLED = "true"
MODEL_ID = "your-model-id"
PATH = "/usr/bin:/bin"
HOME = "/var/tmp/box-readme/tmp"
TMPDIR = "/var/tmp/box-readme/tmp"
PYTHONPATH = "/var/task/vendor"
PYTHONDONTWRITEBYTECODE = "1"
OTEL_TRACES_EXPORTER = "otlp"
OTEL_SERVICE_NAME = "box-readme-agent"
OTEL_SEMCONV_STABILITY_OPT_IN = "gen_ai_latest_experimental,gen_ai_span_attributes_only"

[agent.filesystem]
read = [
  "/usr/lib",
  "/usr/lib64",
  "/var/task/vendor",
  "/var/task/workspace",
  "/var/tmp/box-readme/tmp",
]
read_file = ["/var/task/agent.py"]
exec = ["/var/task/vendor", "/usr/lib/python3.13/lib-dynload"]
write = ["/var/tmp/box-readme/tmp"]

[egress.model]
destinations = ["bedrock-runtime.us-west-2.amazonaws.com"]
secret.ref = "env://AWS_BEARER_TOKEN_BEDROCK"

[telemetry.langfuse]
kind = "langfuse"
destination = "https://cloud.langfuse.com" # 🇪🇺 EU region
secret.ref = "env://LANGFUSE_AUTH"
include = ["trace"]
```

</Details>

Set `MODEL_ID` to your model. If you use another AWS Region, change `AWS_REGION`, the egress destination and the model host in `policy.dw` together.

### Add the entrypoint

Save this entrypoint as `main.py`. It passes the request's prompt to Box:

```python filename="main.py"
import datetime
import os
from pathlib import Path
import subprocess
import sys

ROOT = Path(__file__).resolve().parent
sys.path.insert(0, str(ROOT / "vendor"))

from aws_bedrock_token_generator import provide_token
from bedrock_agentcore.runtime import BedrockAgentCoreApp

WORK = Path("/var/tmp/box-readme")
app = BedrockAgentCoreApp()

@app.entrypoint
def invoke(payload):
    for name in ("state", "tmp", "home"):
        (WORK / name).mkdir(mode=0o700, parents=True, exist_ok=True)
    operator_env = os.environ.copy()
    operator_env["HOME"] = str(WORK / "home")
    operator_env["AWS_BEARER_TOKEN_BEDROCK"] = provide_token(
        region=os.environ["AWS_REGION"],
        expiry=datetime.timedelta(minutes=5),
    )
    result = subprocess.run(
        [
            str(ROOT / "box-core/box"), "run", "--config", str(ROOT / "box.toml"),
            "--", payload["prompt"],
        ],
        env=operator_env, check=True, capture_output=True, text=True, timeout=120,
    )
    return {"output": result.stdout}

if __name__ == "__main__":
    if os.getuid() == 0:
        os.setgroups([])
        os.setgid(991)
        os.setuid(991)
    app.run()
```

Besides starting Box, the entrypoint switches to a non-root user, creates writable directories under `/var/tmp` and creates a short-lived model token from the execution role.

### Build the package

Put the files in one folder:

```text
main.py              # the entrypoint
agent.py             # the agent from the setup steps
box.toml             # the Runtime configuration
policy.dw            # the policy from your Box setup
workspace/README.md  # the README from the setup steps
box-core/            # Box binaries for Linux ARM64
vendor/              # Python dependencies for Linux ARM64
```

Unpack the `box-<version>-linux-arm64.tar.gz` archive of a [Box release](https://github.com/strands-agents/box/releases) into `box-core/`. Then install the dependencies into `vendor/` and zip the folder's contents, so that `main.py` sits at the archive root:

```bash
pip install --target vendor --platform manylinux2014_aarch64 --python-version 3.13 --only-binary=:all: \
  "strands-agents[otel]" bedrock-agentcore aws-bedrock-token-generator
zip -r ../box-readme-agent.zip .
```

### Deploy and invoke

Create the Runtime as a direct code deployment with the Python 3.13 runtime and `main.py` as its entrypoint. The [Box AgentCore deployment guide](https://strandsagents.com/docs/user-guide/box/guides/deploy-to-agentcore-runtime/) shows a complete deployment, including the execution-role permissions for model access.

Set two environment variables on the Runtime: `LANGFUSE_AUTH`, and `DISABLE_ADOT_OBSERVABILITY=true` to turn off the Runtime's built-in telemetry export.

After the Runtime and its DEFAULT endpoint are ready, invoke it with a `prompt` payload. The new trace has the same agent, model and tool structure as the local run.

<Details>
<Summary>Invoke the Runtime with boto3</Summary>

```python
import json
import os
import uuid
import boto3

client = boto3.client("bedrock-agentcore", region_name=os.environ["AWS_REGION"])
response = client.invoke_agent_runtime(
    agentRuntimeArn=os.environ["AGENT_RUNTIME_ARN"],
    runtimeSessionId="box-readme-" + uuid.uuid4().hex,
    contentType="application/json",
    payload=json.dumps({
        "prompt": "Who owns Project Atlas, and when is the release?"
    }).encode(),
)
print(json.loads(response["response"].read())["output"])
```

</Details>

</Steps>

## Box lifecycle traces [#box-lifecycle-traces]

Each Box run sends two traces to Langfuse: the agent trace and a Box lifecycle trace with spans such as `control box_started` and `control box_stopped`. They have different trace IDs. To match them, open an observation's **Metadata** in each trace and compare `resourceAttributes.strands.box.run.id`, which is the same for both traces of a run.

To send only agent traces to Langfuse, export through an [OpenTelemetry Collector](/integrations/native/opentelemetry) that drops spans whose `strands.box.source` resource attribute is not `agent`.

## Interoperability with the Python SDK

You can use this integration together with the Langfuse [SDKs](/docs/observability/sdk/overview) to add additional attributes to the observation.

**Decorator**

The [`@observe()` decorator](/docs/observability/sdk/instrumentation#custom-instrumentation) provides a convenient way to automatically wrap your instrumented code and add additional attributes to the observation.

```python
from langfuse import observe, propagate_attributes, get_client

langfuse = get_client()

@observe()
def my_llm_pipeline(input):
    # Add additional attributes (user_id, session_id, metadata, version, tags) to all spans created within this execution scope
    with propagate_attributes(
        user_id="user_123",
        session_id="session_abc",
        tags=["agent", "my-observation"],
        metadata={"email": "user@langfuse.com"},
        version="1.0.0"
    ):

        # YOUR APPLICATION CODE HERE
        result = call_llm(input)

        return result

# Run the function
my_llm_pipeline("Hi")
```

Learn more about using the Decorator in the [Langfuse SDK instrumentation docs](/docs/observability/sdk/instrumentation#custom-instrumentation).

**Context Manager**

The [Context Manager](/docs/observability/sdk/instrumentation#custom-instrumentation) allows you to wrap your instrumented code using context managers (with `with` statements), which allows you to add additional attributes to the observation.

```python
from langfuse import get_client, propagate_attributes

langfuse = get_client()

with langfuse.start_as_current_observation(
    as_type="span",
    name="my-observation",
    trace_context={"trace_id": "abcdef1234567890abcdef1234567890"},  # Must be 32 hex chars
) as observation:

    # Add additional attributes (user_id, session_id, metadata, version, tags)
    # to all observations created within this execution scope
    with propagate_attributes(
        user_id="user_123",
        session_id="session_abc",
        metadata={"experiment": "variant_a", "env": "prod"},
        version="1.0",
    ):
        # YOUR APPLICATION CODE HERE
        result = call_llm("some input")

# Flush events in short-lived applications
langfuse.flush()
```

Learn more about using the Context Manager in the [Langfuse SDK instrumentation docs](/docs/observability/sdk/instrumentation#custom-instrumentation).

## Troubleshooting

<details>
<summary>No observations appearing</summary>

First, enable [debug mode](/docs/observability/sdk/advanced-features#logging--debugging) in the Python SDK:

```bash
export LANGFUSE_DEBUG="True"
```

Then run your application and check the debug logs:

- **OTel observations appear in the logs:** Your application is instrumented correctly but observations are not reaching Langfuse. To resolve this:
  1. Call [`langfuse.flush()`](/docs/observability/sdk/instrumentation#client-lifecycle--flushing) at the end of your application to ensure all observations are exported.
  2. Verify that you are using the correct API keys and base URL.
- **No OTel spans in the logs:** Your application is not instrumented correctly. Make sure the instrumentation runs before your application code.

</details>

<details>
<summary>Unwanted observations in Langfuse</summary>

The Langfuse SDK is based on OpenTelemetry. Other libraries in your application may emit OTel spans that are not relevant to you. These still count toward your [billable units](/docs/administration/billable-units), so you should filter them out. See [Unwanted spans in Langfuse](/faq/all/unwanted-http-database-spans) for details.

</details>

<details>
<summary>Missing attributes</summary>

Some attributes may be stored in the metadata object of the observation rather than being mapped to the Langfuse data model. If a mapping or integration does not work as expected, please [raise an issue on GitHub](/issues).

</details>

## Next Steps

Once you have instrumented your code, you can manage, evaluate and debug your application:

- [Manage prompts in Langfuse](/docs/prompt-management/get-started)
- [Add evaluation scores](/docs/evaluation/evaluation-methods/scores-via-sdk)
- [Run LLM-as-a-judge Evaluators](/docs/evaluation/evaluation-methods/llm-as-a-judge)
- [Create datasets](/docs/evaluation/experiments/datasets)
- [Create custom dashboards](/docs/metrics/features/custom-dashboards)
- [Test queries in the Playground](/docs/prompt-management/features/playground)

<!-- agent-instructions -->

---

## Agent Instructions

This page is part of the [Langfuse](https://langfuse.com) documentation, published as plain Markdown for AI agents. Every page is available as Markdown by appending `.md` to its URL, or by sending an `Accept: text/markdown` header. This page: `https://langfuse.com/integrations/frameworks/strands-box.md`.

### Querying these docs

If the answer is not on this page, query the documentation instead of guessing:

- **Semantic search** across all Langfuse docs, returning an answer with the relevant pages and excerpts. Ask a specific, self-contained question:

  ```bash
  curl -sG "https://langfuse.com/api/search-docs" --data-urlencode "query=How do I trace a LangGraph agent?"
  ```

- **Index of every page**: <https://langfuse.com/llms.txt>, with per-section indexes [llms-docs.txt](https://langfuse.com/llms-docs.txt), [llms-integrations.txt](https://langfuse.com/llms-integrations.txt), and [llms-self-hosting.txt](https://langfuse.com/llms-self-hosting.txt).

### Before writing Langfuse code

- **Install the [Langfuse Agent Skill](https://langfuse.com/docs/api-and-data-platform/features/agent-skill).** It encodes Langfuse's own best practices for instrumentation, prompt management, and evaluation, and materially improves results.
- **Read [What does a good trace look like?](https://langfuse.com/docs/observability/best-practices.md)** before instrumenting an application.
- **Verify endpoints, parameters, and response fields** against the [OpenAPI spec](https://cloud.langfuse.com/generated/api/openapi.yml), or read the [API reference as Markdown](https://api.reference.langfuse.com/index.md), instead of inferring them from code examples.
- **Use the [Langfuse CLI](https://langfuse.com/docs/api-and-data-platform/features/cli)** (`npx @langfuse/cli api <resource> <action>`) to read or write traces, prompts, datasets, and scores from the terminal.

Found an error in these docs? Please open an issue at <https://github.com/langfuse/langfuse-docs/issues>.
