Get started with TraceLab.
Connect your application. Capture a request. Follow the evidence in your workspace.
On this page
Send your first trace.
This example checks the connection without calling a model. Use an existing TraceLab deployment and run these commands in your application’s folder.
1. Install the SDK
Create a virtual environment so the SDK stays separate from your system Python. Then install the version covered by this guide.
python -m venv .venv
source .venv/bin/activate
python -m pip install tracelab-sdk==0.1.0Already have a virtual environment? Activate it and run the install command. About Python environments
2. Create a project key
Sign in and open Credentials. Give your key a name, choose an expiry, and select Create key. Save the full key when it appears; it is shown only once.
3. Set your connection
Copy the API endpoint from Credentials. Replace both values below with that endpoint and your new key. Set them in the terminal where you will run Python.
export TRACELAB_URL="YOUR_API_ENDPOINT"
export TRACELAB_API_KEY="YOUR_PROJECT_KEY"Use your project API key here. Google, GitHub, and model-provider credentials are different credentials.
4. Record a request
Save this as first_trace.py. It records a real operation, sends the trace when the context closes, and prints the trace ID.
import os
from pathlib import Path
from tracelab import TraceLabClient
client = TraceLabClient(
base_url=os.environ["TRACELAB_URL"],
api_key=os.environ["TRACELAB_API_KEY"],
service_name="my-agent",
spool_dir=Path.home() / ".tracelab" / "spool",
)
try:
with client.trace("first-run", workflow_version="v1") as trace:
with trace.span("normalize-input", "tool", input=" hello tracelab ") as span:
result = " hello tracelab ".strip()
span.set_output(result)
trace.set_output(result)
print("Trace ID:", trace.trace_id)
print("Export error:", client.last_export_error or "none")
finally:
client.close()python first_trace.pyIf the export error is none, open Runs, refresh, and search for first-run or the printed trace ID. The workspace must be connected to the same project.
Credentials
A project key authenticates SDK ingestion. Your Google or GitHub sign-in gives you access to create and manage those keys in the workspace.
- Keep keys in your application’s server environment or secret manager. Never embed them in browser code or commit them to a repository.
- Keys are scoped to one project. Create a separate key for each application or environment so you can revoke access independently.
- Rotate a key by creating its replacement, updating your application, verifying an export, then revoking the old key.
- An expired or revoked key cannot ingest traces. Create a replacement in Credentials.
Trace your agent or RAG workflow.
A trace describes one request. Spans describe the operations inside it: retrieval, model calls, tools, and checks. Nest spans inside the same trace to keep their parent relationships.
Pass a shared TraceLabClient and your existing retrieval and model functions to this wrapper. The retrieval function receives the question; the model function receives the question and retrieved context.
def traced_answer(client, question, retrieve, call_model):
with client.trace(
"answer-question",
workflow_version="prompt-v1",
input={"question": question},
) as trace:
with trace.span("retrieve-context", "retriever", input=question) as span:
context = retrieve(question)
span.set_output(context)
with trace.span(
"generate-answer",
"llm",
input={"question": question, "context": context},
) as span:
answer = call_model(question, context)
span.set_output(answer)
trace.set_output(answer)
return answerReturn JSON-serializable inputs and outputs: strings, numbers, booleans, lists, dictionaries, or None. Extract the relevant fields from provider response objects before recording them.
Reuse the client across requests and call client.close() at application shutdown. The client is synchronous; account for export time in your request path.
| Method | What it records |
|---|---|
client.trace(name, workflow_version=...) | A request and its application or prompt version. |
trace.span(name, kind, input=...) | A timed operation, nested in the current span. |
span.set_output(value) | The operation’s result. |
trace.set_output(value) | The request’s final result. |
span.set_attribute(name, value) | Additional operation metadata. |
span.set_error(message) | A failed operation without raising an exception. |
Useful span kinds include agent, llm, tool, retriever, embedding, and evaluator. Uncaught exceptions inside a span are recorded and re-raised.
Record usage and checks.
Token counts and cost
Inside an LLM span, call set_usage with provider-reported counts. These example counts are illustrative; replace them with the usage returned by your model.
span.set_usage(input_tokens=12, output_tokens=7)You can also supply cached_input_tokens, reasoning_tokens, and cost_usd. The SDK records the cost you supply; it does not calculate model prices.
Explicit evaluation
Implement a check and record it in an evaluator span. Call this helper inside your trace after obtaining an answer. A non-empty answer check is a connection example, not a correctness or faithfulness evaluation.
def check_answer(trace, answer):
with trace.span(
"non-empty-answer",
"evaluator",
input=answer,
attributes={"rubric_version": "non-empty-v1"},
) as span:
passed = isinstance(answer, str) and bool(answer.strip())
span.set_output({"passed": passed, "score": 1 if passed else 0})
if not passed:
span.set_error("Answer is empty.")
return passedInspect the evaluator in the run’s trajectory. Use workflow_version to label changes, rerun the same inputs, and choose a baseline and candidate in Compare runs.
Instrumentation and checks are explicit. The SDK does not automatically intercept model calls, judge answers, create evaluation datasets or experiment reports, or send regression notifications. Automated regression notifications are upcoming.
Export and recovery
A trace exports when its with block exits. Exports are synchronous, with bounded retries for transient failures. An export failure emits a warning and preserves your application’s result or original exception.
Set spool_dir when creating the client to save failed HTTP exports to private JSON files. The Quickstart uses .tracelab/spool inside your home directory, outside your application’s repository. After restoring the connection, replay them with the same client configuration:
sent = client.retry_exports()
print("Recovered traces:", sent)Successfully acknowledged files are removed; unsuccessful files remain. Keep the spool directory writable and outside your repository. Retry errors propagate, so handle them in your recovery job.
Common credential fields and email addresses are redacted before export and spooling. This filtering is conservative and does not detect all sensitive information. Record only the fields your team needs.
Troubleshooting
pip reports “externally-managed-environment”
Your operating system manages its Python installation. Use the virtual environment commands in Quickstart, then run pip inside that environment.
PowerShell cannot activate the environment
You can use the environment’s Python directly without activation:
.\.venv\Scripts\python.exe -m pip install tracelab-sdk==0.1.0
.\.venv\Scripts\python.exe first_trace.pySet the environment variables before running the trace.
The SDK import fails
Install and run with the same Python interpreter. Activate your application’s environment, then check the installed package:
python -m pip show tracelab-sdk
python -c "from tracelab import TraceLabClient; print('SDK available')"A trace does not appear in Runs
Wait for the trace context to close, refresh Runs, and search by trace ID. Confirm that your key belongs to the project open in the workspace. Inspect client.last_export_error and any export warning. Verify the API endpoint from Credentials and check whether a file was saved to your spool directory.
Export reports HTTPStatusError or an authentication failure
An HTTPStatusError means the API returned an unsuccessful HTTP status. The SDK warning reports the error class, not the status code. Confirm that your key is active and was issued by the deployment at your API endpoint. Copy the endpoint from Credentials and create a replacement key if needed. If those values are correct, ask your deployment operator to inspect the server response.
Tokens, cost, or evaluation results are missing
Those fields are explicit. Attach usage with span.set_usage(...), supply cost if needed, and record your own evaluator spans. Instrumentation alone does not score answers. The Evaluations page shows experiment reports; the Python SDK does not create those reports automatically.