Skip to main content

tencentcloud-agentobs-sdk-langchain

中文文档

Observability SDK for LangChain / LangGraph: automatically intercepts LangChain callback and LangGraph node lifecycle events, converts them into OTel spans conforming to the Tencent Cloud CLS GenAI Trace specification, and uploads directly to Tencent Cloud CLS.

  • Zero intrusion: one setup() call (or LangChainInstrumentor().instrument()) completes instrumentation — no changes to business code
  • Faithful trace tree: each graph.invoke() produces a complete trace with an entry → agent → step → chat / tool hierarchy that mirrors the framework's real call structure
  • Concurrency safe: parent-child relationships are derived from the framework's parent_run_id — parallel tool calls and nested sub-agents just work
  • Compliance ready: three content capture modes (full / truncate / off) for strict data-residency requirements
  • Full metrics: token usage, finish_reason, tool error classification, ReAct round tracking

Installation

pip install tencentcloud-agentobs-sdk-langchain

Runtime dependencies are installed automatically. The key ones:

  • langchain-core > 0.1.0 — the target framework being instrumented
  • tencentcloud-cls-sdk-python >= 1.0.8 — CLS upload client

For LangGraph agents you additionally need langgraph, and for LLM calls a provider integration such as langchain-openai.

Requires Python >= 3.9.


Quick Start

A single setup() handles all initialization:

import os
from tencentcloud_agentobs_sdk_langchain import setup, CLSConfig

# 1. Configure your LLM provider (managed by LangChain, not this SDK)
os.environ["OPENAI_API_KEY"] = "sk-xxxx"

# 2. Enable CLS observability (must be called before running any agent)
# Option A: all from environment variables
setup()

# Option B: explicit CLSConfig (unset fields fall back to env vars)
setup(CLSConfig(
    endpoint="ap-guangzhou.cls.tencentcs.com",
    topic_id="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
    secret_id="your_secret_id",
    secret_key="your_secret_key",
))

# 3. Use LangChain / LangGraph as usual
from langchain_core.tools import tool
from langchain_openai import ChatOpenAI
from langgraph.prebuilt import create_react_agent

@tool
def get_weather(city: str) -> str:
    """Look up the weather for a city."""
    return {"Beijing": "Sunny, 26C"}.get(city, "Sunny, 25C")

agent = create_react_agent(ChatOpenAI(model="gpt-4o-mini"), tools=[get_weather])
result = agent.invoke({"messages": [("user", "What's the weather in Beijing?")]})
print(result["messages"][-1].content)

setup() creates a TracerProvider, attaches the CLSCloudExporter, registers instrumentation, and returns the provider (useful if you need to attach additional processors).

Manual wiring (advanced)

from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from tencentcloud_agentobs_sdk_langchain import LangChainInstrumentor
from tencentcloud_agentobs_sdk_langchain.cls_cloud_exporter import CLSCloudExporter

provider = TracerProvider()
provider.add_span_processor(BatchSpanProcessor(CLSCloudExporter()))
LangChainInstrumentor().instrument(tracer_provider=provider)

Configuration

All fields resolve with the priority: explicit CLSConfig value > environment variable > built-in default.

Field Env var Default Meaning
endpoint CLS_ENDPOINT — CLS API endpoint (required)
topic_id CLS_TOPIC_ID — CLS log topic ID (required)
secret_id CLS_SECRET_ID — Tencent Cloud SecretId (required)
secret_key CLS_SECRET_KEY — Tencent Cloud SecretKey (required)
service_name CLS_SERVICE_NAME / OTEL_SERVICE_NAME langchain-app Service / application name
content_mode OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT full full / truncate / off
batch_size CLS_BATCH_SIZE 32 Spans per upload batch (clamped 1–1000)
debug CLS_DEBUG false Verbose SDK logging
local_dump CLS_LOCAL_DUMP false Also write each uploaded batch to a local jsonl
local_dump_file CLS_LOCAL_DUMP_FILE cls_spans.jsonl Local dump file path
user_id CLS_USER_ID — End-user ID written to gen_ai.user.id

SDK logs are written to cls_sdk.log (configurable via CLS_SDK_LOG_FILE / CLS_SDK_LOG_LEVEL), using a rotating file handler.


Span hierarchy

For a LangGraph create_react_agent, one invoke() produces:

entry  enter_application
└ agent  invoke_agent
  ├ step  react round_1
  │  ├ chain  call_model
  │  ├ chain  RunnableSequence
  │  │  ├ chain  Prompt
  │  │  └ chat   <model>
  │  ├ chain  should_continue
  │  └ tool   execute_tool <name>        (one per parallel tool call)
  └ step  react round_2
     └ ...

The tree faithfully reflects LangChain's real callback nesting: chat is nested under its RunnableSequence, tool executions attach directly under the current step, and each entry into the LangGraph agent node opens a new ReAct step.


Examples

See example.py for a minimal end-to-end quick start (LangGraph ReAct agent + setup()).

For a complete LangChain v1 example using langchain.agents.create_agent, including LCEL, retrieval, reranking, and a nested model call, see examples/example_full_v1.py. The existing examples/example_full.py remains as a legacy langgraph.prebuilt.create_react_agent compatibility example.

Deep Agents

Deep Agents is built on LangChain and LangGraph, so the same instrumentation can observe its model, tool, chain, and sub-agent activity. Install the optional dependencies and call setup() before creating the agent:

pip install 'tencentcloud-agentobs-sdk-langchain[deepagents]' langchain-openai
from deepagents import create_deep_agent
from tencentcloud_agentobs_sdk_langchain import setup

setup()  # Reads CLS_ENDPOINT / CLS_TOPIC_ID / CLS_SECRET_ID / CLS_SECRET_KEY
agent = create_deep_agent(model="openai:gpt-4.1-mini", name="deep_agent")
result = agent.invoke({"messages": [{"role": "user", "content": "Hello"}]})

Deep Agents traces use the standard hierarchy entry → agent → step → chat / tool. See examples/deepagents_example.py for a complete runnable example with a custom tool and local span dump enabled.


License

Apache-2.0. See LICENSE.

Metadata

Release files for tencentcloud-agentobs-sdk-langchain 0.0.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for tencentcloud-agentobs-sdk-langchain 0.0.2
File Size Uploaded Provenance
tencentcloud_agentobs_sdk_langchain-0.0.2.tar.gz 53.5 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for tencentcloud-agentobs-sdk-langchain 0.0.2
File Interpreter ABI Platform
tencentcloud_agentobs_sdk_langchain-0.0.2-py3-none-any.whl Python 3 none any Details

Total release size: 102.7 kB

Release files / tencentcloud_agentobs_sdk_langchain-0.0.2.tar.gz

Download URL tencentcloud_agentobs_sdk_langchain-0.0.2.tar.gz
Size 53.5 kB
Tags Source
SHA-256 checksum
How to use checksums
4fb79417352172c2b49e54ee79aa7eb036e75cea8c3138bee6beb99c2b58030c
BLAKE2b-256 checksum
How to use checksums
b1dab72ed7a8fe213734c04384f3fd0aee6feee7f9fe0b37bfb2ae69dd2bd22e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.9

Release files / tencentcloud_agentobs_sdk_langchain-0.0.2-py3-none-any.whl

Download URL tencentcloud_agentobs_sdk_langchain-0.0.2-py3-none-any.whl
Size 49.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
b4710b05b704241711f093902b9e44b0d32b9eecb2adcdeac10f19b66f38125b
BLAKE2b-256 checksum
How to use checksums
f6091d9a12bf309d73c866a7e5dc3a0315e69cb2cce2f5f83b7c9d00feb9e513
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.9

Security for tencentcloud-agentobs-sdk-langchain 0.0.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.0.2 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page