kalibr 1.0.28__py3-none-any.whl → 1.1.2a0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- kalibr/__init__.py +170 -3
- kalibr/__main__.py +3 -203
- kalibr/capsule_middleware.py +108 -0
- kalibr/cli/__init__.py +5 -0
- kalibr/cli/capsule_cmd.py +174 -0
- kalibr/cli/deploy_cmd.py +114 -0
- kalibr/cli/main.py +67 -0
- kalibr/cli/run.py +203 -0
- kalibr/cli/serve.py +59 -0
- kalibr/client.py +293 -0
- kalibr/collector.py +173 -0
- kalibr/context.py +132 -0
- kalibr/cost_adapter.py +222 -0
- kalibr/decorators.py +140 -0
- kalibr/instrumentation/__init__.py +13 -0
- kalibr/instrumentation/anthropic_instr.py +282 -0
- kalibr/instrumentation/base.py +108 -0
- kalibr/instrumentation/google_instr.py +281 -0
- kalibr/instrumentation/openai_instr.py +265 -0
- kalibr/instrumentation/registry.py +153 -0
- kalibr/kalibr.py +144 -230
- kalibr/kalibr_app.py +53 -314
- kalibr/middleware/__init__.py +5 -0
- kalibr/middleware/auto_tracer.py +356 -0
- kalibr/models.py +41 -0
- kalibr/redaction.py +44 -0
- kalibr/schemas.py +116 -0
- kalibr/simple_tracer.py +258 -0
- kalibr/tokens.py +52 -0
- kalibr/trace_capsule.py +296 -0
- kalibr/trace_models.py +201 -0
- kalibr/tracer.py +354 -0
- kalibr/types.py +25 -93
- kalibr/utils.py +198 -0
- kalibr-1.1.2a0.dist-info/METADATA +236 -0
- kalibr-1.1.2a0.dist-info/RECORD +48 -0
- kalibr-1.1.2a0.dist-info/entry_points.txt +2 -0
- kalibr-1.1.2a0.dist-info/licenses/LICENSE +21 -0
- kalibr-1.1.2a0.dist-info/top_level.txt +4 -0
- kalibr_crewai/__init__.py +65 -0
- kalibr_crewai/callbacks.py +539 -0
- kalibr_crewai/instrumentor.py +513 -0
- kalibr_langchain/__init__.py +47 -0
- kalibr_langchain/async_callback.py +850 -0
- kalibr_langchain/callback.py +1064 -0
- kalibr_openai_agents/__init__.py +43 -0
- kalibr_openai_agents/processor.py +554 -0
- kalibr/deployment.py +0 -41
- kalibr/packager.py +0 -43
- kalibr/runtime_router.py +0 -138
- kalibr/schema_generators.py +0 -159
- kalibr/validator.py +0 -70
- kalibr-1.0.28.data/data/examples/README.md +0 -173
- kalibr-1.0.28.data/data/examples/basic_kalibr_example.py +0 -66
- kalibr-1.0.28.data/data/examples/enhanced_kalibr_example.py +0 -347
- kalibr-1.0.28.dist-info/METADATA +0 -175
- kalibr-1.0.28.dist-info/RECORD +0 -19
- kalibr-1.0.28.dist-info/entry_points.txt +0 -2
- kalibr-1.0.28.dist-info/licenses/LICENSE +0 -11
- kalibr-1.0.28.dist-info/top_level.txt +0 -1
- {kalibr-1.0.28.dist-info → kalibr-1.1.2a0.dist-info}/WHEEL +0 -0
kalibr/__init__.py
CHANGED
|
@@ -1,5 +1,172 @@
|
|
|
1
|
-
|
|
1
|
+
"""Kalibr SDK v1.1.0 - Unified LLM Observability & Multi-Model AI Integration Framework
|
|
2
|
+
|
|
3
|
+
This SDK combines:
|
|
4
|
+
1. Full LLM Observability with tracing, cost tracking, and analytics
|
|
5
|
+
2. Multi-Model AI Integration (GPT, Claude, Gemini, Copilot)
|
|
6
|
+
3. One-line deployment with Docker and runtime router
|
|
7
|
+
4. Schema generation for all major AI platforms
|
|
8
|
+
5. **NEW in 1.1.0**: Auto-instrumentation of LLM SDKs (OpenAI, Anthropic, Google)
|
|
9
|
+
|
|
10
|
+
Features:
|
|
11
|
+
- **Auto-Instrumentation**: Zero-config tracing of OpenAI, Anthropic, Google SDK calls
|
|
12
|
+
- **OpenTelemetry**: OTel-compatible spans with OTLP export
|
|
13
|
+
- **Tracing**: Complete telemetry with @trace decorator
|
|
14
|
+
- **Cost Tracking**: Multi-vendor cost calculation (OpenAI, Anthropic, etc.)
|
|
15
|
+
- **Deployment**: One-command deployment to Fly.io, Render, or local
|
|
16
|
+
- **Schema Generation**: Auto-generate schemas for GPT Actions, Claude MCP, Gemini, Copilot
|
|
17
|
+
- **Error Handling**: Automatic error capture with stack traces
|
|
18
|
+
- **Analytics**: ClickHouse-backed analytics and alerting
|
|
19
|
+
|
|
20
|
+
Usage - Auto-Instrumentation (NEW):
|
|
21
|
+
from kalibr import Kalibr
|
|
22
|
+
import openai # Automatically instrumented!
|
|
23
|
+
|
|
24
|
+
app = Kalibr(title="My API")
|
|
25
|
+
|
|
26
|
+
@app.action("chat", "Chat with GPT")
|
|
27
|
+
def chat(message: str):
|
|
28
|
+
# This OpenAI call is automatically traced!
|
|
29
|
+
response = openai.chat.completions.create(
|
|
30
|
+
model="gpt-4",
|
|
31
|
+
messages=[{"role": "user", "content": message}]
|
|
32
|
+
)
|
|
33
|
+
return response.choices[0].message.content
|
|
34
|
+
|
|
35
|
+
Usage - Manual Tracing:
|
|
36
|
+
from kalibr import trace
|
|
37
|
+
|
|
38
|
+
@trace(operation="chat_completion", vendor="openai", model="gpt-4")
|
|
39
|
+
def call_openai(prompt):
|
|
40
|
+
response = openai.chat.completions.create(
|
|
41
|
+
model="gpt-4",
|
|
42
|
+
messages=[{"role": "user", "content": prompt}]
|
|
43
|
+
)
|
|
44
|
+
return response
|
|
45
|
+
|
|
46
|
+
CLI Usage:
|
|
47
|
+
kalibr serve my_app.py # Run locally
|
|
48
|
+
kalibr deploy my_app.py --runtime fly # Deploy to Fly.io
|
|
49
|
+
kalibr run my_app.py # Run with auto-tracing
|
|
50
|
+
kalibr version # Show version
|
|
51
|
+
"""
|
|
52
|
+
|
|
53
|
+
__version__ = "1.1.0-alpha"
|
|
54
|
+
|
|
55
|
+
# Auto-instrument LLM SDKs on import (can be disabled via env var)
|
|
56
|
+
import os
|
|
57
|
+
|
|
58
|
+
# ============================================================================
|
|
59
|
+
# OBSERVABILITY & TRACING (from 1023)
|
|
60
|
+
# ============================================================================
|
|
61
|
+
from .client import KalibrClient
|
|
62
|
+
|
|
63
|
+
# ============================================================================
|
|
64
|
+
# PHASE 1: SDK INSTRUMENTATION & OPENTELEMETRY (v1.1.0)
|
|
65
|
+
# ============================================================================
|
|
66
|
+
from .collector import (
|
|
67
|
+
get_tracer_provider,
|
|
68
|
+
)
|
|
69
|
+
from .collector import is_configured as is_collector_configured
|
|
70
|
+
from .collector import (
|
|
71
|
+
setup_collector,
|
|
72
|
+
)
|
|
73
|
+
from .context import get_parent_span_id, get_trace_id, new_trace_id, trace_context
|
|
74
|
+
from .cost_adapter import (
|
|
75
|
+
AnthropicCostAdapter,
|
|
76
|
+
BaseCostAdapter,
|
|
77
|
+
CostAdapterFactory,
|
|
78
|
+
OpenAICostAdapter,
|
|
79
|
+
)
|
|
80
|
+
from .instrumentation import auto_instrument, get_instrumented_providers
|
|
81
|
+
|
|
82
|
+
# ============================================================================
|
|
83
|
+
# SDK & DEPLOYMENT (from 1.0.30)
|
|
84
|
+
# ============================================================================
|
|
2
85
|
from .kalibr import Kalibr
|
|
86
|
+
from .kalibr_app import KalibrApp
|
|
87
|
+
from .models import EventData, TraceConfig
|
|
88
|
+
from .schemas import (
|
|
89
|
+
generate_copilot_schema,
|
|
90
|
+
generate_gemini_schema,
|
|
91
|
+
generate_mcp_schema,
|
|
92
|
+
get_base_url,
|
|
93
|
+
get_supported_models,
|
|
94
|
+
)
|
|
95
|
+
from .simple_tracer import trace
|
|
96
|
+
from .trace_capsule import TraceCapsule, get_or_create_capsule
|
|
97
|
+
from .tracer import SpanContext, Tracer
|
|
98
|
+
from .types import FileUpload, Session
|
|
99
|
+
from .utils import load_config_from_env
|
|
100
|
+
|
|
101
|
+
if os.getenv("KALIBR_AUTO_INSTRUMENT", "true").lower() == "true":
|
|
102
|
+
# Setup OpenTelemetry collector
|
|
103
|
+
try:
|
|
104
|
+
setup_collector(
|
|
105
|
+
service_name=os.getenv("KALIBR_SERVICE_NAME", "kalibr"),
|
|
106
|
+
file_export=True,
|
|
107
|
+
console_export=os.getenv("KALIBR_CONSOLE_EXPORT", "false").lower() == "true",
|
|
108
|
+
)
|
|
109
|
+
except Exception as e:
|
|
110
|
+
print(f"⚠️ Failed to setup OpenTelemetry collector: {e}")
|
|
111
|
+
|
|
112
|
+
# Auto-instrument available SDKs
|
|
113
|
+
try:
|
|
114
|
+
auto_instrument(["openai", "anthropic", "google"])
|
|
115
|
+
except Exception as e:
|
|
116
|
+
print(f"⚠️ Failed to auto-instrument SDKs: {e}")
|
|
3
117
|
|
|
4
|
-
__all__ = [
|
|
5
|
-
|
|
118
|
+
__all__ = [
|
|
119
|
+
# ========================================================================
|
|
120
|
+
# OBSERVABILITY & TRACING
|
|
121
|
+
# ========================================================================
|
|
122
|
+
# Simple tracing API (recommended)
|
|
123
|
+
"trace",
|
|
124
|
+
# Capsule propagation (Phase 6)
|
|
125
|
+
"TraceCapsule",
|
|
126
|
+
"get_or_create_capsule",
|
|
127
|
+
# Client
|
|
128
|
+
"KalibrClient",
|
|
129
|
+
# Context
|
|
130
|
+
"trace_context",
|
|
131
|
+
"get_trace_id",
|
|
132
|
+
"get_parent_span_id",
|
|
133
|
+
"new_trace_id",
|
|
134
|
+
# Tracer
|
|
135
|
+
"Tracer",
|
|
136
|
+
"SpanContext",
|
|
137
|
+
# Cost Adapters
|
|
138
|
+
"BaseCostAdapter",
|
|
139
|
+
"OpenAICostAdapter",
|
|
140
|
+
"AnthropicCostAdapter",
|
|
141
|
+
"CostAdapterFactory",
|
|
142
|
+
# Models
|
|
143
|
+
"TraceConfig",
|
|
144
|
+
"EventData",
|
|
145
|
+
# Utils
|
|
146
|
+
"load_config_from_env",
|
|
147
|
+
# ========================================================================
|
|
148
|
+
# SDK & DEPLOYMENT
|
|
149
|
+
# ========================================================================
|
|
150
|
+
# SDK Classes
|
|
151
|
+
"Kalibr",
|
|
152
|
+
"KalibrApp",
|
|
153
|
+
# Types
|
|
154
|
+
"FileUpload",
|
|
155
|
+
"Session",
|
|
156
|
+
# Schema Generation
|
|
157
|
+
"get_base_url",
|
|
158
|
+
"generate_mcp_schema",
|
|
159
|
+
"generate_gemini_schema",
|
|
160
|
+
"generate_copilot_schema",
|
|
161
|
+
"get_supported_models",
|
|
162
|
+
# ========================================================================
|
|
163
|
+
# PHASE 1: SDK INSTRUMENTATION & OPENTELEMETRY (v1.1.0)
|
|
164
|
+
# ========================================================================
|
|
165
|
+
# Auto-instrumentation
|
|
166
|
+
"auto_instrument",
|
|
167
|
+
"get_instrumented_providers",
|
|
168
|
+
# OpenTelemetry collector
|
|
169
|
+
"setup_collector",
|
|
170
|
+
"get_tracer_provider",
|
|
171
|
+
"is_collector_configured",
|
|
172
|
+
]
|
kalibr/__main__.py
CHANGED
|
@@ -1,206 +1,6 @@
|
|
|
1
|
-
|
|
2
|
-
import uvicorn
|
|
3
|
-
import sys
|
|
4
|
-
import importlib.util
|
|
5
|
-
from pathlib import Path
|
|
6
|
-
import os
|
|
7
|
-
import requests
|
|
8
|
-
import json
|
|
1
|
+
"""Entry point for python -m kalibr"""
|
|
9
2
|
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
def _load_user_module(file: str):
|
|
13
|
-
file_path = Path(file).resolve()
|
|
14
|
-
if not file_path.exists():
|
|
15
|
-
print(f"❌ Error: {file} not found")
|
|
16
|
-
raise typer.Exit(1)
|
|
17
|
-
spec = importlib.util.spec_from_file_location("user_app", file_path)
|
|
18
|
-
if not spec or not spec.loader:
|
|
19
|
-
print(f"❌ Error: Could not load {file}")
|
|
20
|
-
raise typer.Exit(1)
|
|
21
|
-
module = importlib.util.module_from_spec(spec)
|
|
22
|
-
sys.modules["user_app"] = module
|
|
23
|
-
try:
|
|
24
|
-
spec.loader.exec_module(module)
|
|
25
|
-
except Exception as e:
|
|
26
|
-
print(f"❌ Error loading {file}: {e}")
|
|
27
|
-
raise typer.Exit(1)
|
|
28
|
-
return module
|
|
29
|
-
|
|
30
|
-
@app.command()
|
|
31
|
-
def serve(
|
|
32
|
-
file: str = typer.Argument("kalibr_app.py", help="Python file with Kalibr app"),
|
|
33
|
-
host: str = typer.Option("0.0.0.0", "--host", "-h"),
|
|
34
|
-
port: int = typer.Option(8000, "--port", "-p"),
|
|
35
|
-
base_url: str = typer.Option("http://localhost:8000", "--base-url", "-b"),
|
|
36
|
-
):
|
|
37
|
-
"""Serve a Kalibr-powered API locally."""
|
|
38
|
-
module = _load_user_module(file)
|
|
39
|
-
|
|
40
|
-
# Import Kalibr classes
|
|
41
|
-
from kalibr import Kalibr, KalibrApp
|
|
42
|
-
kalibr_instance = None
|
|
43
|
-
for attr_name in dir(module):
|
|
44
|
-
attr = getattr(module, attr_name)
|
|
45
|
-
if isinstance(attr, Kalibr) or (KalibrApp and isinstance(attr, KalibrApp)):
|
|
46
|
-
kalibr_instance = attr
|
|
47
|
-
kalibr_instance.base_url = base_url
|
|
48
|
-
break
|
|
49
|
-
if not kalibr_instance:
|
|
50
|
-
print(f"❌ Error: No Kalibr/KalibrApp instance found in {file}")
|
|
51
|
-
raise typer.Exit(1)
|
|
52
|
-
|
|
53
|
-
if hasattr(kalibr_instance, 'get_app'):
|
|
54
|
-
fastapi_app = kalibr_instance.get_app()
|
|
55
|
-
elif hasattr(kalibr_instance, 'app'):
|
|
56
|
-
fastapi_app = kalibr_instance.app
|
|
57
|
-
else:
|
|
58
|
-
print(f"❌ Error: Kalibr instance has no get_app() method or app attribute")
|
|
59
|
-
raise typer.Exit(1)
|
|
60
|
-
|
|
61
|
-
is_enhanced = 'KalibrApp' in str(type(kalibr_instance))
|
|
62
|
-
print(f"🚀 Starting {'Enhanced ' if is_enhanced else ''}Kalibr server from {file}")
|
|
63
|
-
print(f"📍 GPT (OpenAPI): {base_url}/openapi.json")
|
|
64
|
-
print(f"📍 Claude (MCP): {base_url}/mcp.json")
|
|
65
|
-
if is_enhanced:
|
|
66
|
-
print(f"📍 Gemini: {base_url}/schemas/gemini")
|
|
67
|
-
print(f"📍 Copilot: {base_url}/schemas/copilot")
|
|
68
|
-
print(f"📍 Supported Models: {base_url}/models/supported")
|
|
69
|
-
print(f"📍 Health Check: {base_url}/health")
|
|
70
|
-
print(f"📍 Swagger UI: {base_url}/docs")
|
|
71
|
-
print(f"🔌 Actions registered: {list(kalibr_instance.actions.keys())}")
|
|
72
|
-
|
|
73
|
-
uvicorn.run(fastapi_app, host=host, port=port)
|
|
74
|
-
|
|
75
|
-
@app.command()
|
|
76
|
-
def package(
|
|
77
|
-
app_dir: str = typer.Option(".", "--app-dir", "-d", help="Directory containing your app"),
|
|
78
|
-
output: str = typer.Option("kalibr_bundle.zip", "--output", "-o", help="Bundle file"),
|
|
79
|
-
models: str = typer.Option("mcp,gpt-actions,gemini,copilot", "--models", "-m", help="Comma-separated models supported")
|
|
80
|
-
):
|
|
81
|
-
"""Create a deployable MCP bundle (code + schemas + metadata)."""
|
|
82
|
-
from kalibr.packager import package_app
|
|
83
|
-
try:
|
|
84
|
-
models_supported = [x.strip() for x in models.split(",") if x.strip()]
|
|
85
|
-
# Version best-effort
|
|
86
|
-
try:
|
|
87
|
-
from kalibr import __version__ as kalibr_version
|
|
88
|
-
except Exception:
|
|
89
|
-
kalibr_version = "unknown"
|
|
90
|
-
bundle_path = package_app(app_dir=app_dir, output=output, models_supported=models_supported, kalibr_version=kalibr_version)
|
|
91
|
-
print(f"📦 Bundle created: {bundle_path}")
|
|
92
|
-
except Exception as e:
|
|
93
|
-
print(f"❌ Packaging error: {e}")
|
|
94
|
-
raise typer.Exit(1)
|
|
95
|
-
|
|
96
|
-
@app.command()
|
|
97
|
-
def deploy(
|
|
98
|
-
file: str = typer.Argument(..., help="Python file to serve/deploy (e.g., kalibr_app.py)"),
|
|
99
|
-
name: str = typer.Option("", "--name", "-n", help="App name (defaults to filename)"),
|
|
100
|
-
runtime: str = typer.Option("local", "--runtime", "-r", help="Runtime: local|fly|render"),
|
|
101
|
-
host: str = typer.Option("0.0.0.0", "--host"),
|
|
102
|
-
port: int = typer.Option(8000, "--port"),
|
|
103
|
-
base_url: str = typer.Option("http://localhost:8000", "--base-url"),
|
|
104
|
-
):
|
|
105
|
-
"""Deploy via runtime router (no hosting burden on Kalibr)."""
|
|
106
|
-
from kalibr.runtime_router import deploy as router_deploy
|
|
107
|
-
file_path = Path(file)
|
|
108
|
-
if not file_path.exists():
|
|
109
|
-
print(f"❌ Error: {file} not found")
|
|
110
|
-
raise typer.Exit(1)
|
|
111
|
-
if not name:
|
|
112
|
-
name = file_path.stem.replace('_', '-').replace('.', '-')
|
|
113
|
-
try:
|
|
114
|
-
result = router_deploy(runtime=runtime, app_name=name, app_file=str(file_path), host=host, port=port, base_url=base_url)
|
|
115
|
-
if result.get("status") in ("success", "started"):
|
|
116
|
-
print("🎉 Deploy OK")
|
|
117
|
-
eps = result.get("endpoints", {})
|
|
118
|
-
if eps:
|
|
119
|
-
print("📍 Endpoints:")
|
|
120
|
-
for k, v in eps.items():
|
|
121
|
-
print(f" - {k}: {v}")
|
|
122
|
-
else:
|
|
123
|
-
print("⚠️ Deploy finished with unknown status:", result)
|
|
124
|
-
except Exception as e:
|
|
125
|
-
print(f"❌ Deployment error: {e}")
|
|
126
|
-
raise typer.Exit(1)
|
|
127
|
-
|
|
128
|
-
@app.command()
|
|
129
|
-
def validate(
|
|
130
|
-
url: str = typer.Option("http://localhost:8000/mcp.json", "--mcp-url", help="URL to MCP manifest"),
|
|
131
|
-
):
|
|
132
|
-
"""Validate MCP manifest against minimal JSON schema & version hint."""
|
|
133
|
-
from kalibr.validator import validate_mcp_manifest
|
|
134
|
-
try:
|
|
135
|
-
resp = requests.get(url, timeout=10)
|
|
136
|
-
resp.raise_for_status()
|
|
137
|
-
manifest = resp.json()
|
|
138
|
-
validate_mcp_manifest(manifest)
|
|
139
|
-
print("✅ MCP manifest looks structurally valid.")
|
|
140
|
-
except Exception as e:
|
|
141
|
-
print(f"❌ Validation failed: {e}")
|
|
142
|
-
raise typer.Exit(1)
|
|
143
|
-
|
|
144
|
-
@app.command()
|
|
145
|
-
def update_schemas():
|
|
146
|
-
"""Stub: instruct users to upgrade SDK and regenerate manifests."""
|
|
147
|
-
from kalibr.validator import update_schemas as _upd
|
|
148
|
-
_upd()
|
|
149
|
-
|
|
150
|
-
@app.command()
|
|
151
|
-
def status(
|
|
152
|
-
app_url: str = typer.Argument(..., help="URL of deployed Kalibr app"),
|
|
153
|
-
verbose: bool = typer.Option(False, "--verbose", "-v", help="Show detailed information")
|
|
154
|
-
):
|
|
155
|
-
"""Check status of a deployed Kalibr app."""
|
|
156
|
-
try:
|
|
157
|
-
health_url = f"{app_url.rstrip('/')}/health"
|
|
158
|
-
response = requests.get(health_url, timeout=10)
|
|
159
|
-
if response.status_code == 200:
|
|
160
|
-
health_data = response.json()
|
|
161
|
-
print(f"✅ App is healthy at {app_url}")
|
|
162
|
-
print(f" Version: {health_data.get('version', 'unknown')}")
|
|
163
|
-
print(f" Features: {health_data.get('features', {})}")
|
|
164
|
-
if verbose:
|
|
165
|
-
schemas = ["mcp.json", "openapi.json", "schemas/gemini", "schemas/copilot"]
|
|
166
|
-
print(f"\n📊 Available AI model schemas:")
|
|
167
|
-
for schema in schemas:
|
|
168
|
-
schema_url = f"{app_url.rstrip('/')}/{schema}"
|
|
169
|
-
try:
|
|
170
|
-
schema_response = requests.get(schema_url, timeout=5)
|
|
171
|
-
status_emoji = "✅" if schema_response.status_code == 200 else "❌"
|
|
172
|
-
model_name = schema.replace(".json", "").replace("schemas/", "")
|
|
173
|
-
print(f" {status_emoji} {model_name.upper()}: {schema_url}")
|
|
174
|
-
except:
|
|
175
|
-
print(f" ❌ {schema}: Connection failed")
|
|
176
|
-
else:
|
|
177
|
-
print(f"❌ App at {app_url} is not responding (HTTP {response.status_code})")
|
|
178
|
-
raise typer.Exit(1)
|
|
179
|
-
except requests.exceptions.RequestException as e:
|
|
180
|
-
print(f"❌ Cannot connect to {app_url}: {e}")
|
|
181
|
-
raise typer.Exit(1)
|
|
182
|
-
|
|
183
|
-
@app.command()
|
|
184
|
-
def version():
|
|
185
|
-
try:
|
|
186
|
-
from kalibr import __version__
|
|
187
|
-
except (ImportError, AttributeError):
|
|
188
|
-
__version__ = "unknown"
|
|
189
|
-
print(f"Kalibr SDK version: {__version__}")
|
|
190
|
-
print("Enhanced multi-model AI integration framework")
|
|
191
|
-
print("Supports: GPT Actions, Claude MCP, Gemini Extensions, Copilot Plugins")
|
|
192
|
-
print("GitHub: https://github.com/devonakelley/kalibr-sdk")
|
|
193
|
-
|
|
194
|
-
def main():
|
|
195
|
-
config_file = Path.home() / ".kalibr" / "config.json"
|
|
196
|
-
if config_file.exists():
|
|
197
|
-
try:
|
|
198
|
-
config = json.loads(config_file.read_text())
|
|
199
|
-
if "api_token" in config and not os.environ.get("KALIBR_TOKEN"):
|
|
200
|
-
os.environ["KALIBR_TOKEN"] = config["api_token"]
|
|
201
|
-
except:
|
|
202
|
-
pass
|
|
203
|
-
app()
|
|
3
|
+
from kalibr.cli.main import app
|
|
204
4
|
|
|
205
5
|
if __name__ == "__main__":
|
|
206
|
-
|
|
6
|
+
app()
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Kalibr Capsule Middleware for FastAPI.
|
|
3
|
+
|
|
4
|
+
Automatically extracts, propagates, and injects trace capsules in HTTP requests.
|
|
5
|
+
|
|
6
|
+
Usage in FastAPI app:
|
|
7
|
+
from kalibr.capsule_middleware import add_capsule_middleware
|
|
8
|
+
|
|
9
|
+
app = FastAPI()
|
|
10
|
+
add_capsule_middleware(app)
|
|
11
|
+
|
|
12
|
+
# Now all requests have request.state.capsule available
|
|
13
|
+
@app.get("/")
|
|
14
|
+
def endpoint(request: Request):
|
|
15
|
+
capsule = request.state.capsule
|
|
16
|
+
# Use capsule...
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
import logging
|
|
20
|
+
|
|
21
|
+
from fastapi import FastAPI, Request
|
|
22
|
+
from starlette.middleware.base import BaseHTTPMiddleware
|
|
23
|
+
from starlette.responses import Response
|
|
24
|
+
|
|
25
|
+
from .trace_capsule import TraceCapsule, get_or_create_capsule
|
|
26
|
+
|
|
27
|
+
logger = logging.getLogger(__name__)
|
|
28
|
+
|
|
29
|
+
CAPSULE_HEADER = "X-Kalibr-Capsule"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class CapsuleMiddleware(BaseHTTPMiddleware):
|
|
33
|
+
"""Middleware that extracts and propagates Kalibr trace capsules.
|
|
34
|
+
|
|
35
|
+
This middleware:
|
|
36
|
+
1. Extracts capsule from incoming X-Kalibr-Capsule header
|
|
37
|
+
2. Attaches capsule to request.state for access in endpoints
|
|
38
|
+
3. Automatically injects updated capsule in response headers
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
async def dispatch(self, request: Request, call_next):
|
|
42
|
+
"""Process request and response with capsule handling.
|
|
43
|
+
|
|
44
|
+
Args:
|
|
45
|
+
request: Incoming HTTP request
|
|
46
|
+
call_next: Next middleware/endpoint in chain
|
|
47
|
+
|
|
48
|
+
Returns:
|
|
49
|
+
Response with X-Kalibr-Capsule header attached
|
|
50
|
+
"""
|
|
51
|
+
# Extract capsule from header (or create new one)
|
|
52
|
+
capsule_header = request.headers.get(CAPSULE_HEADER)
|
|
53
|
+
|
|
54
|
+
if capsule_header:
|
|
55
|
+
capsule = TraceCapsule.from_json(capsule_header)
|
|
56
|
+
logger.debug(f"📦 Received capsule: {capsule}")
|
|
57
|
+
else:
|
|
58
|
+
capsule = TraceCapsule()
|
|
59
|
+
logger.debug(f"📦 Created new capsule: {capsule.trace_id}")
|
|
60
|
+
|
|
61
|
+
# Attach capsule to request state
|
|
62
|
+
request.state.capsule = capsule
|
|
63
|
+
|
|
64
|
+
# Process request
|
|
65
|
+
response = await call_next(request)
|
|
66
|
+
|
|
67
|
+
# Inject updated capsule in response headers
|
|
68
|
+
try:
|
|
69
|
+
capsule_json = capsule.to_json()
|
|
70
|
+
response.headers[CAPSULE_HEADER] = capsule_json
|
|
71
|
+
logger.debug(f"📦 Sending capsule: {capsule}")
|
|
72
|
+
except Exception as e:
|
|
73
|
+
logger.warning(f"⚠️ Failed to serialize capsule: {e}")
|
|
74
|
+
|
|
75
|
+
return response
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def add_capsule_middleware(app: FastAPI) -> None:
|
|
79
|
+
"""Add capsule middleware to FastAPI application.
|
|
80
|
+
|
|
81
|
+
Args:
|
|
82
|
+
app: FastAPI application instance
|
|
83
|
+
|
|
84
|
+
Example:
|
|
85
|
+
app = FastAPI()
|
|
86
|
+
add_capsule_middleware(app)
|
|
87
|
+
"""
|
|
88
|
+
app.add_middleware(CapsuleMiddleware)
|
|
89
|
+
logger.info("✅ Kalibr Capsule middleware added")
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def get_capsule(request: Request) -> TraceCapsule:
|
|
93
|
+
"""Get capsule from request state (convenience function).
|
|
94
|
+
|
|
95
|
+
Args:
|
|
96
|
+
request: FastAPI Request object
|
|
97
|
+
|
|
98
|
+
Returns:
|
|
99
|
+
TraceCapsule attached to request
|
|
100
|
+
|
|
101
|
+
Raises:
|
|
102
|
+
AttributeError: If middleware not installed
|
|
103
|
+
"""
|
|
104
|
+
if not hasattr(request.state, "capsule"):
|
|
105
|
+
logger.warning("⚠️ Capsule middleware not installed, creating new capsule")
|
|
106
|
+
request.state.capsule = TraceCapsule()
|
|
107
|
+
|
|
108
|
+
return request.state.capsule
|
kalibr/cli/__init__.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Capsule Reconstruction CLI Command
|
|
3
|
+
Fetch and export trace capsules from Kalibr Platform
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import json
|
|
7
|
+
import sys
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Optional
|
|
10
|
+
|
|
11
|
+
import requests
|
|
12
|
+
import typer
|
|
13
|
+
from rich import print as rprint
|
|
14
|
+
from rich.console import Console
|
|
15
|
+
from rich.table import Table
|
|
16
|
+
|
|
17
|
+
console = Console()
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def capsule(
|
|
21
|
+
trace_id: str = typer.Argument(..., help="Trace ID to reconstruct capsule for"),
|
|
22
|
+
api_url: Optional[str] = typer.Option(
|
|
23
|
+
None,
|
|
24
|
+
"--api-url",
|
|
25
|
+
"-u",
|
|
26
|
+
help="Kalibr API base URL (default: from env KALIBR_API_URL or http://localhost:8001)",
|
|
27
|
+
envvar="KALIBR_API_URL",
|
|
28
|
+
),
|
|
29
|
+
output: Optional[Path] = typer.Option(
|
|
30
|
+
None,
|
|
31
|
+
"--output",
|
|
32
|
+
"-o",
|
|
33
|
+
help="Output file path (JSON format). If not specified, prints to stdout.",
|
|
34
|
+
),
|
|
35
|
+
export: bool = typer.Option(
|
|
36
|
+
False,
|
|
37
|
+
"--export",
|
|
38
|
+
"-e",
|
|
39
|
+
help="Use export endpoint to download as file",
|
|
40
|
+
),
|
|
41
|
+
pretty: bool = typer.Option(
|
|
42
|
+
True,
|
|
43
|
+
"--pretty/--no-pretty",
|
|
44
|
+
"-p/-np",
|
|
45
|
+
help="Pretty print JSON output",
|
|
46
|
+
),
|
|
47
|
+
):
|
|
48
|
+
"""
|
|
49
|
+
Reconstruct and fetch a trace capsule by trace_id.
|
|
50
|
+
|
|
51
|
+
The capsule contains all linked trace events, aggregated metrics,
|
|
52
|
+
and metadata for a complete execution chain.
|
|
53
|
+
|
|
54
|
+
Examples:
|
|
55
|
+
|
|
56
|
+
# Fetch capsule and display in terminal
|
|
57
|
+
kalibr capsule abc-123-def
|
|
58
|
+
|
|
59
|
+
# Save capsule to file
|
|
60
|
+
kalibr capsule abc-123-def --output capsule.json
|
|
61
|
+
|
|
62
|
+
# Use export endpoint
|
|
63
|
+
kalibr capsule abc-123-def --export --output capsule.json
|
|
64
|
+
|
|
65
|
+
# Specify custom API URL
|
|
66
|
+
kalibr capsule abc-123-def -u https://api.kalibr.io
|
|
67
|
+
"""
|
|
68
|
+
# Determine API base URL
|
|
69
|
+
base_url = api_url or "http://localhost:8001"
|
|
70
|
+
base_url = base_url.rstrip("/")
|
|
71
|
+
|
|
72
|
+
# Build endpoint URL
|
|
73
|
+
if export:
|
|
74
|
+
endpoint = f"{base_url}/api/capsule/{trace_id}/export"
|
|
75
|
+
else:
|
|
76
|
+
endpoint = f"{base_url}/api/capsule/{trace_id}"
|
|
77
|
+
|
|
78
|
+
console.print(f"[cyan]Fetching capsule for trace_id:[/cyan] [bold]{trace_id}[/bold]")
|
|
79
|
+
console.print(f"[dim]Endpoint: {endpoint}[/dim]")
|
|
80
|
+
|
|
81
|
+
try:
|
|
82
|
+
# Make API request
|
|
83
|
+
response = requests.get(endpoint, timeout=30)
|
|
84
|
+
response.raise_for_status()
|
|
85
|
+
|
|
86
|
+
# Parse response
|
|
87
|
+
capsule_data = response.json()
|
|
88
|
+
|
|
89
|
+
# Display summary
|
|
90
|
+
console.print("\n[green]✓ Capsule reconstructed successfully[/green]\n")
|
|
91
|
+
|
|
92
|
+
# Create summary table
|
|
93
|
+
table = Table(title="Capsule Summary", show_header=False)
|
|
94
|
+
table.add_column("Field", style="cyan", no_wrap=True)
|
|
95
|
+
table.add_column("Value", style="white")
|
|
96
|
+
|
|
97
|
+
table.add_row("Capsule ID", capsule_data.get("capsule_id", "N/A"))
|
|
98
|
+
table.add_row("Total Cost (USD)", f"${capsule_data.get('total_cost_usd', 0):.6f}")
|
|
99
|
+
table.add_row("Total Latency (ms)", str(capsule_data.get("total_latency_ms", 0)))
|
|
100
|
+
table.add_row("Hop Count", str(capsule_data.get("hop_count", 0)))
|
|
101
|
+
table.add_row("Providers", ", ".join(capsule_data.get("providers", [])))
|
|
102
|
+
table.add_row("Reconstructed At", capsule_data.get("reconstructed_at", "N/A"))
|
|
103
|
+
|
|
104
|
+
console.print(table)
|
|
105
|
+
|
|
106
|
+
# Output to file or stdout
|
|
107
|
+
if output:
|
|
108
|
+
output_path = Path(output)
|
|
109
|
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
|
110
|
+
|
|
111
|
+
with open(output_path, "w") as f:
|
|
112
|
+
if pretty:
|
|
113
|
+
json.dump(capsule_data, f, indent=2, sort_keys=True)
|
|
114
|
+
else:
|
|
115
|
+
json.dump(capsule_data, f)
|
|
116
|
+
|
|
117
|
+
console.print(f"\n[green]✓ Capsule saved to:[/green] {output_path}")
|
|
118
|
+
else:
|
|
119
|
+
# Print to stdout
|
|
120
|
+
console.print("\n[bold]Capsule Data:[/bold]")
|
|
121
|
+
if pretty:
|
|
122
|
+
rprint(json.dumps(capsule_data, indent=2, sort_keys=True))
|
|
123
|
+
else:
|
|
124
|
+
print(json.dumps(capsule_data))
|
|
125
|
+
|
|
126
|
+
# Display event details
|
|
127
|
+
events = capsule_data.get("events", [])
|
|
128
|
+
if events:
|
|
129
|
+
console.print(f"\n[bold]Events ({len(events)}):[/bold]")
|
|
130
|
+
event_table = Table()
|
|
131
|
+
event_table.add_column("Trace ID", style="cyan")
|
|
132
|
+
event_table.add_column("Provider", style="yellow")
|
|
133
|
+
event_table.add_column("Model", style="magenta")
|
|
134
|
+
event_table.add_column("Operation", style="blue")
|
|
135
|
+
event_table.add_column("Duration (ms)", justify="right", style="green")
|
|
136
|
+
event_table.add_column("Cost (USD)", justify="right", style="green")
|
|
137
|
+
event_table.add_column("Status", style="white")
|
|
138
|
+
|
|
139
|
+
for event in events:
|
|
140
|
+
event_table.add_row(
|
|
141
|
+
event.get("trace_id", "")[:12] + "...",
|
|
142
|
+
event.get("provider", "N/A"),
|
|
143
|
+
event.get("model_id", "N/A")[:20],
|
|
144
|
+
event.get("operation", "N/A"),
|
|
145
|
+
str(event.get("duration_ms", 0)),
|
|
146
|
+
f"${event.get('cost_usd', 0):.6f}",
|
|
147
|
+
event.get("status", "N/A"),
|
|
148
|
+
)
|
|
149
|
+
|
|
150
|
+
console.print(event_table)
|
|
151
|
+
|
|
152
|
+
return 0
|
|
153
|
+
|
|
154
|
+
except requests.exceptions.HTTPError as e:
|
|
155
|
+
if e.response.status_code == 404:
|
|
156
|
+
console.print(f"[red]✗ Capsule not found for trace_id: {trace_id}[/red]")
|
|
157
|
+
console.print("[yellow]Make sure the trace_id exists and has been ingested.[/yellow]")
|
|
158
|
+
else:
|
|
159
|
+
console.print(f"[red]✗ API Error ({e.response.status_code}):[/red] {e.response.text}")
|
|
160
|
+
return 1
|
|
161
|
+
|
|
162
|
+
except requests.exceptions.ConnectionError:
|
|
163
|
+
console.print(f"[red]✗ Connection Error:[/red] Unable to connect to {base_url}")
|
|
164
|
+
console.print("[yellow]Make sure the Kalibr backend is running and accessible.[/yellow]")
|
|
165
|
+
return 1
|
|
166
|
+
|
|
167
|
+
except requests.exceptions.Timeout:
|
|
168
|
+
console.print("[red]✗ Timeout:[/red] Request took too long to complete")
|
|
169
|
+
return 1
|
|
170
|
+
|
|
171
|
+
except Exception as e:
|
|
172
|
+
console.print(f"[red]✗ Unexpected Error:[/red] {str(e)}")
|
|
173
|
+
console.print("[yellow]Run with --help for usage information[/yellow]")
|
|
174
|
+
return 1
|