SDK y API

Guía del SDK de Python

Instale el SDK de OpenTelemetry de KLA para Python y envíe una primera traza al Lineage Explorer.

1 min de lectura301 palabras

El paquete del SDK de KLA para Python es kla-otel-python. Impórtelo como kla_otel_python. Inicializa OpenTelemetry, añade los atributos GenAI de KLA y exporta ayudantes para middleware de FastAPI, instrumentación de LangChain, muestreo y publicación de evaluaciones.

Instalación

pip install kla-otel-python

Para el inicio rápido con FastAPI:

pip install "kla-otel-python[fastapi]" uvicorn

Defina el servicio y el collector antes de que arranque la aplicación:

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

Primera traza con FastAPI

Cargue el SDK antes de crear la aplicación y cualquier cliente de modelo.

# 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}"}

Ejecútelo:

uvicorn main:app --reload
curl -s http://localhost:8000/messages \
  -H 'content-type: application/json' \
  -d '{"prompt":"Summarize the claim"}'

Abra KLA Control Plane, vaya al Lineage Explorer y filtre por claims-agent-api. El span debería incluir gen_ai.system, gen_ai.request.model y los atributos de uso de tokens.

LangChain

Instale el extra de LangChain y habilite el instrumentador antes de construir chains, agentes o herramientas.

pip install "kla-otel-python[langchain]"
import kla_otel_python
from kla_otel_python.instrumentors import LangChainInstrumentor

LangChainInstrumentor().instrument()

Para spans de modelo explícitos:

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"),
        },
    )

Verificación del paquete

El dry-run del paquete del SDK se ejecuta en CI con:

python -m pip install --upgrade build twine
python -m build
python -m twine check dist/*
Guía del SDK de Python | Developer Docs | KLA Control Plane