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 runs an agent in a contained process with declared file, network and credential access.
What is Langfuse? Langfuse is an open-source AI engineering platform. It provides tracing, debugging, evaluation, and monitoring capabilities for AI agents and LLM applications. Use Langfuse Cloud (hosted by Langfuse, free tier, no infrastructure to run) or self-host it.
Strands Agents records the agent's work as OpenTelemetry traces. Box forwards those traces to Langfuse with your project's API keys.
![]()
Setup steps
In this tutorial, we will use the Box Python agent setup and use its ~/box-tutorial folder. The steps below add tracing.
Add tracing to the agent
Install tracing support in the agent's Python environment:
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:
"""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. Set them as one public-key:secret-key value in the operator environment, which is the shell that launches Box:
export LANGFUSE_AUTH="pk-lf-...:sk-lf-..."Configure Box export
Add these values to the agent's existing environment in 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:
[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.
Use Box's generic OTLP target instead
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:
[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.
Run the task
Put these lines in ~/box-tutorial/my-project/README.md:
Project Atlas
Owner: Maya
Release day: TuesdayIn 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:
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 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.
Run on AgentCore Runtime
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 is one such environment; the Box documentation 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.
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.
Complete box.toml for AgentCore Runtime
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"]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:
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:
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 ARM64Unpack the box-<version>-linux-arm64.tar.gz archive of a Box release into box-core/. Then install the dependencies into vendor/ and zip the folder's contents, so that main.py sits at the archive root:
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 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.
Invoke the Runtime with boto3
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"])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 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 to add additional attributes to the observation.
The @observe() decorator provides a convenient way to automatically wrap your instrumented code and add additional attributes to the observation.
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.
The Context Manager allows you to wrap your instrumented code using context managers (with with statements), which allows you to add additional attributes to the observation.
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.
Troubleshooting
No observations appearing
First, enable debug mode in the Python SDK:
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:
- Call
langfuse.flush()at the end of your application to ensure all observations are exported. - Verify that you are using the correct API keys and base URL.
- Call
- No OTel spans in the logs: Your application is not instrumented correctly. Make sure the instrumentation runs before your application code.
Unwanted observations in Langfuse
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, so you should filter them out. See Unwanted spans in Langfuse for details.
Missing attributes
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.
Next Steps
Once you have instrumented your code, you can manage, evaluate and debug your application:
Manage prompts in Langfuse
Add evaluation scores
Run LLM-as-a-judge Evaluators
Create datasets
Create custom dashboards
Test queries in the Playground
Last updated on