Python - LangChain Integration
The recommended way to track LangChain pipelines in production is using the explicit PaygentLangChainCallback. This approach provides fine-grained control over tracking context and enables seamless multi-model pipeline monitoring.
Production Callback Integration
Attach the PaygentLangChainCallback to your model instances to automatically track tokens, costs, and performance across every step of your chain.
langchain_production.py
1import os
2import paygent_sdk
3from paygent_sdk import PaygentLangChainCallback
4from langchain_openai import ChatOpenAI
5from langchain_google_genai import ChatGoogleGenerativeAI
6from langchain_core.prompts import ChatPromptTemplate
7from langchain_core.output_parsers import StrOutputParser
8from dotenv import load_dotenv
9
10load_dotenv()
11
12# 1. Initialize Paygent
13paygent_sdk.init(os.getenv("PAYGENT_API_KEY"))
14
15# 2. Create the production-ready callback
16# Use this single tracker for the entire pipeline
17paygent_cb = PaygentLangChainCallback(
18 paygent_client=paygent_sdk._global_client,
19 indicator="article-generator-pipeline",
20 external_agent_id="writer-agent", # Get this from your Agent settings in Paygent
21 external_customer_id="customer-99",
22 external_customer_name="Global Media" # Optional: Auto-creates customer in Paygent
23)
24
25# 3. Attach to your models
26llm = ChatOpenAI(
27 model="gpt-4o",
28 temperature=0,
29 callbacks=[paygent_cb]
30)
31
32# 4. Use in a standard LangChain Expression Language (LCEL) chain
33prompt = ChatPromptTemplate.from_template("Summarize this topic: {topic}")
34chain = prompt | llm | StrOutputParser()
35
36if __name__ == "__main__":
37 result = chain.invoke({"topic": "Quantum Computing"})
38 print(f"Summary: {result}")
39 # ✅ Every invocation is now tracked in your Paygent dashboardWhy use callbacks?
- Named Context: Group different parts of your application under distinct indicators.
- Auto-Onboarding: Automatically create customers in Paygent when they first interact with your AI.
- Multi-Model: Track usage across OpenAI, Anthropic, Gemini, and Mistral in a single unified view.
Multi-Model Pipeline Example
Complex workflows often involve multiple LLM providers. By passing the same callback instance to every model, you maintain a consistent billing context.
multi_model_pipeline.py
1# Attach the same callback to different providers
2openai_llm = ChatOpenAI(model="gpt-4o", callbacks=[paygent_cb])
3gemini_llm = ChatGoogleGenerativeAI(model="gemini-2.5-flash", callbacks=[paygent_cb])
4
5# Both models will now contribute usage data to the same 'article-generator-pipeline' indicatorWas this page helpful?
Need help? Contact us at support@withpaygent.com