Files
comet-ml--opik/sdks/python/examples/dynamic_tracing_example.py
T
wehub-resource-sync 5a558eb09e
TypeScript SDK Compatibility V1.x E2E Tests / Select Node version matrix (push) Has been cancelled
TypeScript SDK Compatibility V1.x E2E Tests / TypeScript SDK Compatibility V1.x E2E Tests Node ${{matrix.node_version}} (push) Has been cancelled
TypeScript SDK E2E Tests / TypeScript SDK E2E Tests Node ${{matrix.node_version}} (push) Has been cancelled
Opik Optimizer - E2E Tests / build-opik (push) Has been cancelled
TypeScript SDK Compatibility V1.x E2E Tests / build-opik (push) Has been cancelled
Python SDK E2E Tests / Select Python version matrix (push) Has been cancelled
Python SDK E2E Tests / Python SDK E2E Tests ${{matrix.python_version}} (push) Has been cancelled
Python SDK E2E Tests / build-opik (push) Has been cancelled
Python SDK Compatibility V1.x E2E Tests / Select Python version matrix (push) Has been cancelled
Python SDK Compatibility V1.x E2E Tests / Python SDK Compatibility V1.x E2E Tests ${{matrix.python_version}} (push) Has been cancelled
Python SDK Compatibility V1.x E2E Tests / build-opik (push) Has been cancelled
TypeScript SDK E2E Tests / Select Node version matrix (push) Has been cancelled
TypeScript SDK E2E Tests / build-opik (push) Has been cancelled
Opik Optimizer - E2E Tests / Opik Optimizer E2E Tests Python ${{matrix.python_version}} (push) Has been cancelled
Opik Optimizer - E2E Tests / Opik Optimizer Integration Smoke Tests (push) Has been cancelled
🐙 Code Quality / detect (push) Has been cancelled
🐙 Code Quality / lint (${{ matrix.leg.name }}) (push) Has been cancelled
🐙 Code Quality / summary (push) Has been cancelled
TypeScript SDK Library Integration Tests / Check Secrets (push) Has been cancelled
TypeScript SDK Library Integration Tests / opik-vercel (Vercel AI SDK / eve) (push) Has been cancelled
SDK Library Integration Tests Runner / Check Secrets (push) Has been cancelled
SDK Library Integration Tests Runner / Missed OpenAI API Key Warning (push) Has been cancelled
SDK Library Integration Tests Runner / Build (push) Has been cancelled
SDK Library Integration Tests Runner / openai_tests (push) Has been cancelled
SDK Library Integration Tests Runner / langchain_tests (push) Has been cancelled
SDK Library Integration Tests Runner / langchain_legacy_tests (push) Has been cancelled
SDK Library Integration Tests Runner / llama_index_tests (push) Has been cancelled
SDK Library Integration Tests Runner / anthropic_tests (push) Has been cancelled
SDK Library Integration Tests Runner / mistral_tests (push) Has been cancelled
SDK Library Integration Tests Runner / groq_tests (push) Has been cancelled
SDK Library Integration Tests Runner / aisuite_tests (push) Has been cancelled
SDK Library Integration Tests Runner / haystack_tests (push) Has been cancelled
SDK Library Integration Tests Runner / dspy_tests (push) Has been cancelled
SDK Library Integration Tests Runner / crewai_v0_tests (push) Has been cancelled
SDK Library Integration Tests Runner / crewai_v1_tests (push) Has been cancelled
SDK Library Integration Tests Runner / genai_tests (push) Has been cancelled
SDK Library Integration Tests Runner / adk_tests (push) Has been cancelled
SDK Library Integration Tests Runner / adk_legacy_1_3_0_tests (push) Has been cancelled
SDK Library Integration Tests Runner / evaluation_metrics_tests (push) Has been cancelled
SDK Library Integration Tests Runner / bedrock_tests (push) Has been cancelled
SDK Library Integration Tests Runner / litellm_tests (push) Has been cancelled
SDK Library Integration Tests Runner / harbor_tests (push) Has been cancelled
SDK Library Integration Tests Runner / Slack Notification (push) Has been cancelled
Lint Opik Helm Chart / render-equality (push) Has been cancelled
Opik Optimizer - Unit Tests / Opik Optimizer Unit Tests Python ${{matrix.python_version}} (push) Has been cancelled
Python BE E2E Tests / Python BE E2E (push) Has been cancelled
Python Backend Tests / run-python-backend-tests (push) Has been cancelled
Python SDK Unit Tests / Python SDK Unit Tests ${{matrix.python_version}} (push) Has been cancelled
Release Drafter / update_release_draft (push) Has been cancelled
SDK E2E Libraries Integration Tests / Check Secrets (push) Has been cancelled
SDK E2E Libraries Integration Tests / Missed OpenAI API Key Warning (push) Has been cancelled
SDK E2E Libraries Integration Tests / build-opik (push) Has been cancelled
SDK E2E Libraries Integration Tests / E2E Lib Integration Python ${{matrix.python_version}} (push) Has been cancelled
TypeScript SDK Integration Build & Publish / build-and-publish (opik-gemini) (push) Has been cancelled
TypeScript SDK Integration Build & Publish / build-and-publish (opik-langchain) (push) Has been cancelled
TypeScript SDK Integration Build & Publish / build-and-publish (opik-openai) (push) Has been cancelled
TypeScript SDK Integration Build & Publish / build-and-publish (opik-otel) (push) Has been cancelled
TypeScript SDK Integration Build & Publish / build-and-publish (opik-vercel) (push) Has been cancelled
TypeScript SDK Build & Publish / build-and-publish (push) Has been cancelled
TypeScript SDK Unit Tests / Test on Node ${{ matrix.node-version }} (push) Has been cancelled
Backend Tests / discover-tests (push) Has been cancelled
Backend Tests / ${{ matrix.name }} (push) Has been cancelled
Build and Publish SDK / build-and-publish (push) Has been cancelled
Build Opik Docker Images / set-version (push) Has been cancelled
Build Opik Docker Images / build-backend (push) Has been cancelled
Build Opik Docker Images / build-sandbox-executor-python (push) Has been cancelled
Build Opik Docker Images / build-python-backend (push) Has been cancelled
Build Opik Docker Images / build-frontend (push) Has been cancelled
Build Opik Docker Images / create-git-tag (push) Has been cancelled
ClickHouse Migration Cluster Check / validate-clickhouse-migrations (push) Has been cancelled
Docs - Publish / run (push) Has been cancelled
E2E Tests - Post Merge (v2) / 🧪 E2E v2 Tests (${{ github.event.inputs.tier || 't1' }}) (push) Has been cancelled
E2E Tests - Post Merge (v2) / 📢 Slack Notification (push) Has been cancelled
Frontend Unit Tests / Test on Node 20 (push) Has been cancelled
Guardrails E2E Tests / Select Python version matrix (push) Has been cancelled
Guardrails E2E Tests / Guardrails E2E Tests ${{matrix.python_version}} (push) Has been cancelled
Guardrails E2E Tests / 📢 Slack Notification (push) Has been cancelled
Guardrails Backend Unit Tests / Guardrails Backend Unit Tests (push) Has been cancelled
Guardrails Backend Unit Tests / 📢 Slack Notification (push) Has been cancelled
Lint Opik Helm Chart / lint-helm-chart (Helm v3.21.0) (push) Has been cancelled
Lint Opik Helm Chart / lint-helm-chart (Helm v4.2.0) (push) Has been cancelled
Lint Opik Helm Chart / unittest-helm-chart (push) Has been cancelled
chore: import upstream snapshot with attribution
2026-07-13 13:25:44 +08:00

200 lines
6.1 KiB
Python

"""
Dynamic Tracing Control Example
This example demonstrates how to enable and disable Opik tracing at runtime
without modifying your instrumented code or restarting your application.
"""
import time
from typing import Dict, Any
import opik
from opik.integrations import openai as openai_integration
def simulate_openai_client() -> object:
"""Create a mock OpenAI client for demonstration."""
class MockClient:
def __init__(self) -> None:
self.chat = type(
"Chat",
(),
{
"completions": type(
"Completions",
(),
{"create": lambda self, **kwargs: {"content": "Mock response"}},
)()
},
)()
def __getattr__(self, name: str) -> Any:
return None
return MockClient()
@opik.track(name="llm_call")
def call_llm(prompt: str, user_type: str = "free") -> str:
"""Simulate an LLM call with user type information."""
client = simulate_openai_client()
response = client.chat.completions.create(
model="gpt-3.5-turbo", messages=[{"role": "user", "content": prompt}]
)
return f"Response for {user_type} user: {response['content']}"
@opik.track(name="data_processing")
def process_data(data: Dict[str, Any]) -> Dict[str, Any]:
"""Simulate data processing that we want to trace."""
result = {"processed": True, "item_count": len(data)}
time.sleep(0.01) # Simulate work
return result
def measure_performance(func, *args, iterations: int = 100) -> float:
"""Measure average execution time of a function."""
start_time = time.time()
for _ in range(iterations):
func(*args)
end_time = time.time()
return (end_time - start_time) / iterations
def main() -> None:
"""Demonstrate dynamic tracing capabilities."""
print("=== Opik Dynamic Tracing Demo ===\n")
# 1. Basic enable/disable functionality
print("1. Basic Runtime Control")
print("-" * 30)
print(f"Initial tracing state: {opik.is_tracing_active()}")
# Disable tracing
opik.set_tracing_active(False)
print(f"After disabling: {opik.is_tracing_active()}")
# Call traced function - no traces will be created
result = call_llm("Hello world", "free")
print(f"Function result (no tracing): {result}")
# Re-enable tracing
opik.set_tracing_active(True)
print(f"After enabling: {opik.is_tracing_active()}\n")
# 2. Conditional tracing based on user type
print("2. Conditional Tracing by User Type")
print("-" * 40)
def handle_request(prompt: str, user_type: str) -> str:
"""Handle request with conditional tracing."""
# Only trace premium users
should_trace = user_type == "premium"
opik.set_tracing_active(should_trace)
print(f"Processing {user_type} user request (tracing: {should_trace})")
return call_llm(prompt, user_type)
# Process different user types
handle_request("What is AI?", "free")
handle_request("Explain quantum computing", "premium")
handle_request("Hello", "free")
print()
# 3. Sampling-based tracing
print("3. Sampling-Based Tracing (10% of requests)")
print("-" * 50)
import random
def handle_request_with_sampling(request_id: int) -> Dict[str, Any]:
"""Handle request with 10% sampling rate."""
should_trace = random.random() < 0.1 # 10% sampling
opik.set_tracing_active(should_trace)
data = {"request_id": request_id, "data": list(range(10))}
result = process_data(data)
if should_trace:
print(f"Request {request_id}: TRACED")
else:
print(f"Request {request_id}: not traced")
return result
# Process multiple requests
for i in range(10):
handle_request_with_sampling(i)
print()
# 4. Performance comparison
print("4. Performance Impact Comparison")
print("-" * 40)
test_data = {"items": list(range(100))}
# Measure with tracing enabled
opik.set_tracing_active(True)
time_with_tracing = measure_performance(process_data, test_data, iterations=50)
# Measure with tracing disabled
opik.set_tracing_active(False)
time_without_tracing = measure_performance(process_data, test_data, iterations=50)
print(f"Average time with tracing: {time_with_tracing * 1000:.2f}ms")
print(f"Average time without tracing: {time_without_tracing * 1000:.2f}ms")
if time_with_tracing > time_without_tracing:
overhead = (
(time_with_tracing - time_without_tracing) / time_without_tracing
) * 100
print(f"Tracing overhead: {overhead:.1f}%")
print()
# 5. Integration tracking control
print("5. Integration Tracking Control")
print("-" * 40)
# Simulate tracking an OpenAI client
mock_client = simulate_openai_client()
# Disable tracing before setting up integration
opik.set_tracing_active(False)
openai_integration.track_openai(mock_client)
print(
"OpenAI client tracking setup with tracing disabled - no instrumentation applied"
)
# Enable tracing and set up integration
opik.set_tracing_active(True)
openai_integration.track_openai(mock_client)
print("OpenAI client tracking setup with tracing enabled - instrumentation applied")
print()
# 6. Reset to configuration default
print("6. Reset to Configuration Default")
print("-" * 40)
# Override runtime setting
opik.set_tracing_active(False)
print(f"Runtime override active: {opik.is_tracing_active()}")
# Reset to config default
opik.reset_tracing_to_config_default()
print(f"After reset to config: {opik.is_tracing_active()}")
print("(This will use the value from OPIK_TRACK_DISABLE or config file)")
print("\n=== Demo Complete ===")
print("Key benefits of dynamic tracing:")
print("• Zero code changes required")
print("• Runtime performance optimization")
print("• Flexible sampling strategies")
print("• Easy debugging and troubleshooting")
if __name__ == "__main__":
main()