forked from LayerLens/stratix-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasic_trace.py
More file actions
218 lines (177 loc) · 6.85 KB
/
Copy pathbasic_trace.py
File metadata and controls
218 lines (177 loc) · 6.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
#!/usr/bin/env python
"""
Basic Trace Operations -- LayerLens Python SDK Sample
=====================================================
Demonstrates trace operations using the LayerLens Python SDK:
1. Upload traces from a JSONL file.
2. List traces with filtering and pagination.
3. Get a single trace by ID.
4. Get available trace sources.
5. Delete a trace.
This sample ports the ateam core/basic_trace.py sample to use the
layerlens SDK client instead of raw httpx calls.
Prerequisites
-------------
* ``pip install layerlens --index-url https://sdk.layerlens.ai/package``
* Set ``LAYERLENS_STRATIX_API_KEY`` environment variable
* A traces.jsonl file (see samples/data/traces/ for format)
Usage
-----
::
export LAYERLENS_STRATIX_API_KEY=your-api-key
python basic_trace.py
python basic_trace.py --file /path/to/traces.jsonl
"""
from __future__ import annotations
import os
import sys
import json
import logging
import argparse
import tempfile
from layerlens import Stratix
# ---------------------------------------------------------------------------
# Logging
# ---------------------------------------------------------------------------
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
)
logger = logging.getLogger("layerlens.samples.basic_trace")
# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
description="Trace CRUD operations with the LayerLens Python SDK.",
)
parser.add_argument(
"--file",
default="",
help="Path to a JSONL trace file to upload. If omitted, sample data is generated.",
)
parser.add_argument(
"--skip-delete",
action="store_true",
default=False,
help="Keep traces on the platform after the sample completes.",
)
parser.add_argument(
"--page-size",
type=int,
default=10,
help="Number of traces to list per page (default: 10).",
)
return parser
# ---------------------------------------------------------------------------
# Sample data
# ---------------------------------------------------------------------------
def generate_sample_traces() -> str:
"""Generate a temporary JSONL file with sample trace data.
Returns the path to the temporary file.
"""
traces = [
{
"input": [{"role": "user", "content": "What is the capital of France?"}],
"output": "The capital of France is Paris.",
"metadata": {"model": "gpt-4o", "temperature": 0.7, "source": "sdk-sample"},
},
{
"input": [{"role": "user", "content": "Explain photosynthesis briefly."}],
"output": "Photosynthesis is the process by which plants convert sunlight, water, and CO2 into glucose and oxygen.",
"metadata": {"model": "gpt-4o", "temperature": 0.7, "source": "sdk-sample"},
},
{
"input": [{"role": "user", "content": "What is binary search?"}],
"output": "Binary search is an efficient algorithm that finds a target value in a sorted array by repeatedly dividing the search interval in half, achieving O(log n) time complexity.",
"metadata": {"model": "gpt-4o", "temperature": 0.7, "source": "sdk-sample"},
},
]
fd, path = tempfile.mkstemp(suffix=".jsonl")
with os.fdopen(fd, "w") as f:
for trace in traces:
f.write(json.dumps(trace) + "\n")
return path
# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------
def main() -> None:
parser = build_parser()
args = parser.parse_args()
# --- Initialize SDK client ---
try:
client = Stratix()
except Exception as exc:
logger.error("Failed to initialize client: %s", exc)
sys.exit(1)
logger.info("Connected to LayerLens (org=%s, project=%s)", client.organization_id, client.project_id)
# --- Step 1: Upload traces ---
logger.info("=" * 60)
logger.info("Step 1: Upload traces")
logger.info("=" * 60)
temp_file = None
if args.file:
if not os.path.isfile(args.file):
logger.error("File not found: %s", args.file)
sys.exit(1)
file_path = args.file
else:
file_path = generate_sample_traces()
temp_file = file_path
logger.info("Generated sample traces at %s", file_path)
try:
result = client.traces.upload(file_path)
if result and result.trace_ids:
logger.info("Uploaded %d trace(s)", len(result.trace_ids))
for tid in result.trace_ids:
logger.info(" trace_id=%s", tid)
else:
logger.warning("Upload returned no trace IDs")
sys.exit(1)
except Exception as exc:
logger.error("Upload failed: %s", exc)
sys.exit(1)
finally:
if temp_file and os.path.exists(temp_file):
os.unlink(temp_file)
uploaded_ids = result.trace_ids
# --- Step 2: List traces ---
logger.info("=" * 60)
logger.info("Step 2: List traces")
logger.info("=" * 60)
response = client.traces.get_many(page_size=args.page_size, sort_by="created_at", sort_order="desc")
if response:
logger.info("Found %d trace(s) (total=%d)", response.count, response.total_count)
for trace in response.traces[:5]:
logger.info(" - %s: %s", trace.id, getattr(trace, "filename", "N/A"))
else:
logger.warning("No traces found")
# --- Step 3: Get a single trace ---
logger.info("=" * 60)
logger.info("Step 3: Get a single trace")
logger.info("=" * 60)
trace = client.traces.get(uploaded_ids[0])
if trace:
logger.info("Trace %s retrieved successfully", trace.id)
logger.info(" Data keys: %s", list(trace.data.keys()) if hasattr(trace, "data") and trace.data else "N/A")
else:
logger.warning("Could not retrieve trace %s", uploaded_ids[0])
# --- Step 4: Get sources ---
logger.info("=" * 60)
logger.info("Step 4: Get trace sources")
logger.info("=" * 60)
sources = client.traces.get_sources()
logger.info("Available sources: %s", sources if sources else "(none)")
# --- Step 5: Delete traces ---
if not args.skip_delete:
logger.info("=" * 60)
logger.info("Step 5: Delete uploaded traces")
logger.info("=" * 60)
for tid in uploaded_ids:
deleted = client.traces.delete(tid)
logger.info(" Deleted %s: %s", tid, deleted)
else:
logger.info("Skipping deletion (--skip-delete). Trace IDs: %s", ", ".join(uploaded_ids))
logger.info("Sample complete.")
if __name__ == "__main__":
main()