Skip to main content

LangChain Integration

Add Treeship verification to LangChain agents using callbacks or tools.

Setup

pip install treeship-sdk langchain langchain-openai

Callback Handler

Create a Treeship callback to automatically attest all LLM calls:
from langchain.callbacks.base import BaseCallbackHandler
from treeship_sdk import Treeship

ts = Treeship()

class TreeshipCallback(BaseCallbackHandler):
    def __init__(self, agent_name: str = "langchain-agent"):
        self.agent_name = agent_name
    
    def on_llm_end(self, response, **kwargs):
        ts.attest(
            agent=self.agent_name,
            action=f"LLM response generated",
            inputs_hash=ts.hash({"response_id": response.llm_output.get("id")})
        )
    
    def on_tool_end(self, output, **kwargs):
        ts.attest(
            agent=self.agent_name,
            action=f"Tool executed: {kwargs.get('name', 'unknown')}",
            inputs_hash=ts.hash({"output": str(output)[:200]})
        )

# Use the callback
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(
    model="gpt-4",
    callbacks=[TreeshipCallback("my-agent")]
)

As a Tool

Add Treeship as a tool your agent can use:
from langchain.tools import Tool
from treeship_sdk import Treeship

ts = Treeship()

def create_attestation(action_description: str) -> str:
    """Create a verified attestation of an action."""
    attestation = ts.attest(
        agent="langchain-agent",
        action=action_description
    )
    return f"Verified: {attestation.verify_url}"

treeship_tool = Tool(
    name="create_verification",
    description="Create a tamper-proof record of an important action. Use this after making decisions that need proof.",
    func=create_attestation
)

# Add to your agent
from langchain.agents import AgentExecutor, create_openai_tools_agent

agent = create_openai_tools_agent(llm, [treeship_tool, ...other_tools], prompt)
executor = AgentExecutor(agent=agent, tools=[treeship_tool, ...other_tools])

Chain Verification

Verify entire chain executions:
from langchain.chains import LLMChain
from treeship_sdk import Treeship

ts = Treeship()

def run_verified_chain(chain: LLMChain, inputs: dict):
    # Run the chain
    result = chain.run(inputs)
    
    # Attest the execution
    attestation = ts.attest(
        agent="langchain-chain",
        action=f"Chain executed: {chain.prompt.template[:50]}...",
        inputs_hash=ts.hash(inputs)
    )
    
    return {
        "result": result,
        "verification": attestation.verify_url
    }

LCEL Integration

For LangChain Expression Language (LCEL):
from langchain_core.runnables import RunnableLambda
from treeship_sdk import Treeship

ts = Treeship()

def attest_step(data):
    ts.attest(
        agent="lcel-agent",
        action=f"Step completed",
        inputs_hash=ts.hash(data)
    )
    return data

# Add to your chain
chain = prompt | llm | RunnableLambda(attest_step) | output_parser

Next Steps