-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasic_usage.py
More file actions
257 lines (181 loc) · 7.33 KB
/
basic_usage.py
File metadata and controls
257 lines (181 loc) · 7.33 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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
"""
Basic usage examples for msgtrace SDK.
Demonstrates:
- Context managers (sync and async)
- Decorators
- Attributes (unified MsgTraceAttributes)
- Drop-in replacement for msgflux telemetry
"""
import asyncio
import os
from msgtrace.sdk import MsgTraceAttributes, Spans
# ========== Configuration ==========
# Enable telemetry
os.environ["MSGTRACE_TELEMETRY_ENABLED"] = "true"
os.environ["MSGTRACE_OTLP_ENDPOINT"] = "http://localhost:8000/api/v1/traces/export"
os.environ["MSGTRACE_SERVICE_NAME"] = "example-app"
# ========== Example 1: Basic Context Manager ==========
def example_basic_context():
"""Basic span with context manager."""
with Spans.span_context("chat_completion"):
# Set attributes
MsgTraceAttributes.set_operation_name("chat")
MsgTraceAttributes.set_model("gpt-5")
MsgTraceAttributes.set_temperature(0.7)
# Simulate AI operation
print("Processing chat completion...")
# Set usage
MsgTraceAttributes.set_usage(input_tokens=100, output_tokens=50)
# Set cost
MsgTraceAttributes.set_cost(input_cost=0.003, output_cost=0.0015)
# ========== Example 2: Flow and Module Spans ==========
def example_flow_and_modules():
"""Hierarchical flow with modules."""
with Spans.init_flow("user_query_flow"):
MsgTraceAttributes.set_workflow_name("query_processing")
# Module 1: Retrieve
with Spans.init_module("vector_search"):
MsgTraceAttributes.set_operation_name("embedding")
MsgTraceAttributes.set_model("text-embedding-3-small")
print("Searching vectors...")
# Module 2: Generate
with Spans.init_module("response_generation"):
MsgTraceAttributes.set_operation_name("chat")
MsgTraceAttributes.set_model("gpt-5")
print("Generating response...")
# ========== Example 3: Function Decorators ==========
@Spans.instrument("process_query")
def process_query(query: str):
"""Instrumented function."""
MsgTraceAttributes.set_operation_name("chat")
MsgTraceAttributes.set_model("gpt-5")
print(f"Processing: {query}")
return f"Response to: {query}"
@Spans.set_tool_attributes("search_database", description="Search knowledge base")
@Spans.instrument("tool_search")
def search_database(query: str):
"""Tool with attributes."""
print(f"Searching database for: {query}")
return ["result1", "result2"]
# ========== Example 4: Async Operations ==========
@Spans.ainstrument("async_chat")
async def async_chat_completion(prompt: str):
"""Async chat completion."""
MsgTraceAttributes.set_operation_name("chat")
MsgTraceAttributes.set_model("gpt-5")
MsgTraceAttributes.set_prompt(prompt)
# Simulate async API call
await asyncio.sleep(0.1)
MsgTraceAttributes.set_completion("Here's the response")
MsgTraceAttributes.set_usage(input_tokens=50, output_tokens=30)
return "Response"
async def example_async_flow():
"""Async flow with context managers."""
async with Spans.ainit_flow("async_user_flow"):
MsgTraceAttributes.set_workflow_name("async_processing")
async with Spans.ainit_module("async_retrieval"):
print("Async retrieval...")
await asyncio.sleep(0.05)
async with Spans.ainit_module("async_generation"):
result = await async_chat_completion("What is AI?")
print(f"Result: {result}")
# ========== Example 5: Tool Calling ==========
def example_tool_calling():
"""Example with tool calls."""
with Spans.span_context("agent_execution"):
MsgTraceAttributes.set_operation_name("agent")
MsgTraceAttributes.set_agent_name("research_agent")
# Set tool call
MsgTraceAttributes.set_tool_name("search_web")
MsgTraceAttributes.set_tool_call_id("call_001")
MsgTraceAttributes.set_tool_call_arguments(
{"query": "latest AI research", "num_results": 5}
)
# Simulate tool execution
print("Calling tool: search_web")
# Set tool response
MsgTraceAttributes.set_tool_response({"results": ["result1", "result2", "result3"]})
# Set msgtrace-specific tool metadata
MsgTraceAttributes.set_tool_callings(
[
{
"id": "call_001",
"name": "search_web",
"arguments": {"query": "latest AI research", "num_results": 5},
}
]
)
MsgTraceAttributes.set_tool_responses([{"id": "call_001", "content": "Found 3 results..."}])
# ========== Example 6: Error Handling ==========
def example_error_handling():
"""Automatic exception recording."""
try:
with Spans.span_context("risky_operation"):
MsgTraceAttributes.set_operation_name("chat")
raise ValueError("Something went wrong!")
except ValueError as e:
print(f"Caught error: {e}")
# Exception automatically recorded in span
# ========== Example 7: Custom Attributes ==========
def example_custom_attributes():
"""Using custom msgtrace attributes."""
with Spans.span_context("custom_operation"):
# Standard GenAI
MsgTraceAttributes.set_operation_name("chat")
MsgTraceAttributes.set_model("gpt-5")
# MsgTrace custom
MsgTraceAttributes.set_user_id("user_123")
MsgTraceAttributes.set_session_id("session_456")
MsgTraceAttributes.set_environment("production")
MsgTraceAttributes.set_version("1.0.0")
MsgTraceAttributes.set_cache_hit(True)
MsgTraceAttributes.set_retry_count(2)
# Fully custom
MsgTraceAttributes.set_custom("business_metric", 42.5)
MsgTraceAttributes.set_custom("metadata", {"key1": "value1", "key2": "value2"})
# ========== Example 8: Drop-in Replacement for msgflux ==========
def example_msgflux_replacement():
"""
Drop-in replacement for msgflux telemetry.
Just change imports:
FROM: from msgflux.telemetry import Spans, MsgTraceAttributes
TO: from msgtrace.sdk import Spans, MsgTraceAttributes
"""
# Exactly same API as msgflux
with Spans.init_flow("my_flow"):
MsgTraceAttributes.set_operation_name("chat")
MsgTraceAttributes.set_model("gpt-5")
with Spans.init_module("my_module"):
MsgTraceAttributes.set_usage(input_tokens=100, output_tokens=50)
# ========== Run Examples ==========
def main():
"""Run all examples."""
print("=" * 60)
print("msgtrace SDK Examples")
print("=" * 60)
print("\n1. Basic context manager:")
example_basic_context()
print("\n2. Flow and modules:")
example_flow_and_modules()
print("\n3. Function decorators:")
result = process_query("What is AI?")
print(f"Result: {result}")
print("\n4. Tool with decorators:")
results = search_database("AI research")
print(f"Results: {results}")
print("\n5. Tool calling:")
example_tool_calling()
print("\n6. Error handling:")
example_error_handling()
print("\n7. Custom attributes:")
example_custom_attributes()
print("\n8. msgflux replacement:")
example_msgflux_replacement()
print("\n" + "=" * 60)
print("Running async examples...")
print("=" * 60)
# Run async examples
asyncio.run(example_async_flow())
print("\n✅ All examples completed!")
if __name__ == "__main__":
main()