LangGraph y LangChain

Traza grafos de LangGraph y cadenas de LangChain con costo por nodo, feature y cliente, observando tus llamadas a Bedrock o enviándolas por el gateway.

Actualizada el 26 de septiembre de 2026

opentoken.init() instrumenta LangChain (la base de LangGraph): ejecuciones del grafo, nodos, cadenas y cada llamada al modelo con tokens. Las llamadas hechas con langchain-aws también se trazan a nivel de Bedrock, y se cuentan una sola vez.

1. Instala

shell
pip install "getopentoken[langchain,bedrock]" langgraph langchain-aws

2. Entorno

Crea una llave de ingesta en API keys (alcance Ingest) y expórtala como OT_INGEST_KEY.

.env
# OT_INGEST_KEY: an ingest key from API keys (scope: Ingest). Keep it in your secret store.
export OTEL_EXPORTER_OTLP_ENDPOINT="https://getopentoken.com/api/otel"
export OTEL_SERVICE_NAME="support-agent"

3. Observa tu grafo

Tus llamadas al modelo siguen yendo a Bedrock en tu cuenta:

agent.py
import opentoken

opentoken.init()

from langchain_aws import ChatBedrockConverse
from langgraph.graph import END, START, MessagesState, StateGraph

llm = ChatBedrockConverse(model="us.amazon.nova-lite-v1:0")


def answer(state: MessagesState):
    return {"messages": [llm.invoke(state["messages"])]}


graph = StateGraph(MessagesState)
graph.add_node("answer", answer)
graph.add_edge(START, "answer")
graph.add_edge("answer", END)
app = graph.compile()

with opentoken.context(feature="support", customer="acme"):
    result = app.invoke({"messages": [("user", "Summarize our refund policy in one sentence.")]})
print(result["messages"][-1].content)

Aplica presupuestos por el gateway (opcional)

chat_model() devuelve un ChatOpenAI conectado al gateway con fail-open a Bedrock. Úsalo donde LangChain reciba un chat model, incluidos los agentes prearmados de LangGraph.

agent.py
import opentoken
from opentoken.adapters.langchain import chat_model
from langgraph.graph import END, START, MessagesState, StateGraph

opentoken.init(base_url="https://getopentoken.com/v1")  # OT_API_KEY for the gateway, OT_INGEST_KEY for traces

# ChatOpenAI wired to the gateway, with fail-open straight to Bedrock in your account if we're slow or down.
llm = chat_model("amazon/nova-lite")


def answer(state: MessagesState):
    return {"messages": [llm.invoke(state["messages"])]}


graph = StateGraph(MessagesState)
graph.add_node("answer", answer)
graph.add_edge(START, "answer")
graph.add_edge("answer", END)

with opentoken.context(feature="support"):
    result = graph.compile().invoke({"messages": [("user", "Say hello in one sentence.")]})
print(result["messages"][-1].content)

No apuntes un ChatOpenAI común al gateway mientras init() instrumenta: el gateway mediría la llamada y el span la reportaría otra vez. chat_model() marca sus spans para que cada llamada se cuente una vez.