Created
June 17, 2025 19:14
-
-
Save ohmeow/71b8c4f85fe3b4d541c7e034e2368bb4 to your computer and use it in GitHub Desktop.
Demonstrates how to retrieve child span metrics based on trace-level metadata in Braintrust
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
This script demonstrates how to retrieve child span metrics based on trace-level metadata. | |
Given a project ID and a specific span name, it queries the Braintrust API to find | |
traces matching certain metadata criteria and extracts metrics for the specified child span. | |
""" | |
import argparse | |
import os | |
import requests | |
from dotenv import load_dotenv | |
load_dotenv(override=True) | |
# Make sure to replace this with your stack's Universal API URL if you are self-hosting | |
API_URL = "https://api.braintrust.dev/" | |
headers = {"Authorization": "Bearer " + os.environ["BRAINTRUST_API_KEY"]} | |
if __name__ == "__main__": | |
parser = argparse.ArgumentParser() | |
parser.add_argument("--project-id", type=str, required=True) | |
parser.add_argument("--span-name", type=str, default="root") | |
args = parser.parse_args() | |
# Find all rows matching a certain metadata value. | |
query= f""" | |
select: span_attributes, metrics | |
from: project_logs('{args.project_id}') traces | |
filter: metadata.orgName = 'qawolf' | |
limit:10 | |
""" | |
response = requests.post(f"{API_URL}/btql", headers=headers, json={"query": query}).json() | |
durations = [] | |
for trace in response["data"]: | |
# print(trace) | |
if trace["span_attributes"]["name"] == args.span_name: | |
metrics = trace["metrics"] | |
if metrics.get("end") and metrics.get("start"): | |
duration = metrics['end'] - metrics['start'] | |
durations.append(duration) | |
print(f"Duration: {duration}ms") | |
print("-"*100) | |
else: | |
print("Start or end not found for this span") | |
print("-"*100) | |
print(f"\nAverage duration: {sum(durations)/len(durations)}ms\n") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment