Guide du SDK Python
Installez le SDK OpenTelemetry de KLA pour Python et envoyez une première trace vers le Lineage Explorer.
Le paquet du SDK KLA pour Python est kla-otel-python. Importez-le sous le nom kla_otel_python. Il initialise OpenTelemetry, ajoute les attributs GenAI de KLA et exporte des utilitaires pour le middleware FastAPI, l'instrumentation LangChain, l'échantillonnage et la publication d'évaluations.
Installation
pip install kla-otel-python
Pour le démarrage rapide avec FastAPI :
pip install "kla-otel-python[fastapi]" uvicorn
Définissez le service et le collector avant le démarrage de l'application :
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
Première trace avec FastAPI
Chargez le SDK avant de créer l'application et tout client de modèle.
# 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}"}
Exécutez-le :
uvicorn main:app --reload
curl -s http://localhost:8000/messages \
-H 'content-type: application/json' \
-d '{"prompt":"Summarize the claim"}'
Ouvrez KLA Control Plane, allez dans le Lineage Explorer et filtrez sur claims-agent-api. Le span doit inclure gen_ai.system, gen_ai.request.model et les attributs d'usage de tokens.
LangChain
Installez l'extra LangChain et activez l'instrumenteur avant de construire des chains, des agents ou des outils.
pip install "kla-otel-python[langchain]"
import kla_otel_python
from kla_otel_python.instrumentors import LangChainInstrumentor
LangChainInstrumentor().instrument()
Pour des spans de modèle explicites :
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"),
},
)
Vérification du paquet
Le dry-run du paquet SDK s'exécute en CI avec :
python -m pip install --upgrade build twine
python -m build
python -m twine check dist/*
