Python SDK Leitfaden
Installieren Sie das KLA OpenTelemetry SDK für Python und senden Sie einen ersten Trace an den Lineage Explorer.
Das KLA Python SDK-Paket ist kla-otel-python. Importieren Sie es als kla_otel_python. Es initialisiert OpenTelemetry, ergänzt KLA-GenAI-Attribute und exportiert Helfer für FastAPI-Middleware, LangChain-Instrumentierung, Sampling und das Veröffentlichen von Evaluationen.
Installation
pip install kla-otel-python
Für den FastAPI-Schnellstart:
pip install "kla-otel-python[fastapi]" uvicorn
Setzen Sie Service und Collector, bevor die Anwendung startet:
export OTEL_SERVICE_NAME=claims-agent-api
export KLA_TENANT_ID=kpmg-reporting
export OTEL_EXPORTER_OTLP_ENDPOINT=<kla-otlp-grpc-endpoint>
export KLA_PII_MASK=true
Erster Trace mit FastAPI
Laden Sie das SDK, bevor Sie die App und Modell-Clients erstellen.
# main.py
import kla_otel_python
from fastapi import FastAPI
from kla_otel_python import add_genai_attributes, tracer
from kla_otel_python.middleware import KLATracingMiddleware
from kla_otel_python.semantic_conventions import GenAIAttributes
app = FastAPI()
app.add_middleware(KLATracingMiddleware)
@app.post("/messages")
async def create_message(payload: dict):
with tracer.start_as_current_span("agent.reply") as span:
prompt = str(payload.get("prompt", ""))
add_genai_attributes(
span,
{
GenAIAttributes.SYSTEM: "openai",
GenAIAttributes.REQUEST_MODEL: "gpt-4o-mini",
GenAIAttributes.USAGE_PROMPT_TOKENS: 24,
GenAIAttributes.USAGE_COMPLETION_TOKENS: 12,
GenAIAttributes.USAGE_TOTAL_TOKENS: 36,
},
)
return {"response": f"Handled: {prompt}"}
Ausführen:
uvicorn main:app --reload
curl -s http://localhost:8000/messages \
-H 'content-type: application/json' \
-d '{"prompt":"Summarize the claim"}'
Öffnen Sie die KLA Control Plane, gehen Sie zum Lineage Explorer und filtern Sie nach claims-agent-api. Der Span sollte gen_ai.system, gen_ai.request.model und die Token-Usage-Attribute enthalten.
LangChain
Installieren Sie das LangChain-Extra und aktivieren Sie den Instrumentor, bevor Sie Chains, Agents oder Tools erstellen.
pip install "kla-otel-python[langchain]"
import kla_otel_python
from kla_otel_python.instrumentors import LangChainInstrumentor
LangChainInstrumentor().instrument()
Für explizite Modell-Spans:
from kla_otel_python import add_genai_attributes, tracer
from kla_otel_python.semantic_conventions import GenAIAttributes
with tracer.start_as_current_span("langchain.agent.answer") as span:
result = chain.invoke({"input": "Review this transaction"})
add_genai_attributes(
span,
{
GenAIAttributes.SYSTEM: "openai",
GenAIAttributes.REQUEST_MODEL: "gpt-4o-mini",
GenAIAttributes.USAGE_TOTAL_TOKENS: result.get("usage", {}).get("total_tokens"),
},
)
Paketprüfung
Der Dry-Run des SDK-Pakets läuft in CI mit:
python -m pip install --upgrade build twine
python -m build
python -m twine check dist/*
