Skip to main content

LangChain + LangGraph Integration with xpander.ai

This guide demonstrates how to integrate LangChain and LangGraph with xpander.ai to create powerful ReAct agents with access to over 2000 pre-built tools and services.
๐Ÿš€ Quick Start Template: Import this template directly into xpander.ai
๐Ÿ““ Prefer Jupyter Notebook? You can also follow along with our interactive notebook: LangChain + xpander.ai Example Notebook - it contains all the code and explanations in a single executable file.

What Youโ€™ll Build

By the end of this tutorial, youโ€™ll have a LangChain ReAct agent that can:
  • ๐Ÿ” Search the web using Tavily Search with advanced filtering
  • ๐Ÿ“ง Send emails with rich formatting and attachments
  • ๐Ÿง  Use intelligent reasoning through LangGraphโ€™s ReAct pattern
  • ๐ŸŽฏ Follow custom instructions from your xpander agent configuration
  • โšก Optimize token usage with xpanderโ€™s output schema filtering

Prerequisites

Before starting, make sure you have:
  • xpander.ai account: Sign up here
  • Python 3.8 or higher
  • OpenAI API key
  • Basic knowledge of Python and LangChain

Step 1: Installation

First, install the required dependencies:
pip install "xpander-sdk" "langchain[openai]" langgraph python-dotenv

Step 2: Environment Setup

Create a .env file in your project directory:
# Required - OpenAI API
OPENAI_API_KEY="your_openai_api_key_here"

# Required - xpander.ai Platform Configuration  
XPANDER_API_KEY="your_xpander_api_key"
XPANDER_ORGANIZATION_ID="your_organization_id"
XPANDER_AGENT_ID="your_agent_id"

Where to find your xpander credentials:

  1. API Key: Go to xpander Settings โ†’ API Keys
  2. Organization ID: Found in your organization settings or browser URL
  3. Agent ID: Create or select an agent in the xpander platform
Make sure to add .env to your .gitignore file to avoid committing sensitive credentials.

Step 3: Set Up Your xpander Agent

In the xpander.ai platform:
  1. Create a new agent or use an existing one
  2. Add tools to your agent:
    • Tavily Search - for web search capabilities
    • Send Email - for email functionality
    • Any other tools you need from the 2000+ available
  3. Configure tool output filtering to optimize performance
  4. Set up agent instructions and goals

Step 4: Create the Integration

Create a new Python file langchain_xpander_agent.py:
import os
from dotenv import load_dotenv
from langchain_openai import ChatOpenAI
from langgraph.prebuilt import create_react_agent
from langchain_core.messages import SystemMessage
from xpander_sdk import Agents

# Load environment variables
load_dotenv()

def validate_environment():
    """Validate that all required environment variables are set"""
    required_vars = [
        "OPENAI_API_KEY",
        "XPANDER_API_KEY", 
        "XPANDER_ORGANIZATION_ID",
        "XPANDER_AGENT_ID"
    ]
    
    for var in required_vars:
        if not os.getenv(var):
            raise KeyError(f"Missing required environment variable: {var}")
    
    print("โœ… All required environment variables are set!")

def create_system_prompt(instructions):
    """Convert xpander agent instructions to system prompt"""
    parts = []
    
    if hasattr(instructions, 'general') and instructions.general:
        parts.append(f"System: {instructions.general}")
    
    if hasattr(instructions, 'goal_str') and instructions.goal_str:
        parts.append(f"Goals:\n{instructions.goal_str}")
    
    if hasattr(instructions, 'instructions') and instructions.instructions:
        instr_list = "\n".join([f"- {instr}" for instr in instructions.instructions])
        parts.append(f"Instructions:\n{instr_list}")
    
    return "\n\n".join(parts)

def main():
    # Validate environment
    validate_environment()
    
    # Initialize xpander agent
    print("๐Ÿ”ง Loading xpander agent configuration...")
    xpander_agent = Agents().get(agent_id=os.getenv("XPANDER_AGENT_ID"))
    
    print(f"๐Ÿ“ฆ Loaded agent with {len(xpander_agent.tools.functions)} tools")
    print(f"๐Ÿค– Using model: {xpander_agent.model_name}")
    
    # Initialize the language model
    llm = ChatOpenAI(model=xpander_agent.model_name, temperature=0)
    
    # Create system prompt from xpander agent instructions
    system_prompt = create_system_prompt(xpander_agent.instructions)
    print(f"๐Ÿ“‹ System Prompt:\n{system_prompt}\n")
    
    # Create a ReAct agent with xpander tools
    agent = create_react_agent(
        llm, 
        xpander_agent.tools.functions
    )
    
    print(f"๐Ÿš€ LangChain ReAct agent created successfully!")
    
    # Test the agent
    test_query = "search for information about xpander.ai and summarize what you find"
    print(f"\n๐Ÿ“‹ Test Query: {test_query}")
    print("๐Ÿค” Agent thinking...\n")
    
    # Stream the agent's response
    for chunk in agent.stream({
        "messages": [
            ("system", system_prompt),
            ("user", test_query)
        ]
    }):
        # Extract and display the agent's response
        if "agent" in chunk and chunk["agent"].get("messages"):
            messages = chunk["agent"]["messages"]
            for message in messages:
                if hasattr(message, 'content') and message.content:
                    print(f"๐Ÿค– Agent: {message.content}")

if __name__ == "__main__":
    main()

Step 5: Advanced Features

Custom Agent Instructions

You can enhance your agent by adding custom instructions in the xpander platform:
# The agent will automatically use instructions configured in xpander
# Examples of what you can configure:
# - Role: "You are a helpful research assistant"
# - Goals: "Help users find accurate information and provide summaries"
# - Instructions: ["Always verify information", "Provide sources", "Be concise"]

Multi-Tool Workflows

Your agent can chain multiple tools together:
# Example query that uses multiple tools
complex_query = """
Search for the latest AI developments, 
then send an email summary to team@company.com
"""

response = agent.invoke({
    "messages": [
        ("system", system_prompt),
        ("user", complex_query)
    ]
})

Output Schema Filtering

xpanderโ€™s advanced output schema filtering helps you:
  • Reduce token usage by removing unnecessary data
  • Remove PII and sensitive information
  • Focus AI attention on relevant response parts
  • Prevent data exposure of irrelevant fields
Configure this in your xpander agentโ€™s tool settings.

Step 6: Running Your Agent

Execute your agent:
python langchain_xpander_agent.py
You should see output similar to:
โœ… All required environment variables are set!
๐Ÿ”ง Loading xpander agent configuration...
๐Ÿ“ฆ Loaded agent with 2 tools
๐Ÿค– Using model: gpt-4
๐Ÿ“‹ System Prompt:
System: You are a helpful AI assistant...

๐Ÿš€ LangChain ReAct agent created successfully!
๐Ÿ“‹ Test Query: search for information about xpander.ai and summarize what you find
๐Ÿค” Agent thinking...

๐Ÿค– Agent: I'll search for information about xpander.ai for you...

Available Tools

This example includes powerful pre-configured tools:
ToolDescriptionKey Features
๐Ÿ” Tavily SearchAdvanced web searchConfigurable search depth, Result filtering, Answer generation, Topic-specific search
๐Ÿ“ง Send EmailEmail capabilitiesRich text support, Attachment handling, Template support

Customization Options

Adding More Tools

  1. Go to your xpander agent configuration
  2. Browse the tool library (2000+ available tools)
  3. Add tools to your agent
  4. Theyโ€™ll automatically be available in your LangChain agent

Using Different Models

# Use different OpenAI models
llm = ChatOpenAI(model="gpt-4o", temperature=0.7)

# Or use other providers supported by LangChain
from langchain_anthropic import ChatAnthropic
llm = ChatAnthropic(model="claude-3-sonnet-20240229")

Custom Message Handling

def process_agent_response(response):
    """Custom processing of agent responses"""
    for message in response["messages"]:
        if message.type == "ai":
            print(f"๐Ÿค– AI: {message.content}")
        elif message.type == "tool":
            print(f"๐Ÿ”ง Tool Result: {message.content}")

Troubleshooting

Common Issues

Environment Variable Errors
KeyError: Missing required environment variable: XPANDER_API_KEY
โ†’ Ensure all required variables are set in your .env file Tool Configuration Errors
Error: 2 validation errors for TavilySearchService...
โ†’ Check your tool configuration in the xpander platform Authentication Errors
401 Unauthorized
โ†’ Verify your API keys are correct and have proper permissions

Performance Tips

  1. Use Output Filtering: Configure tool output schemas to reduce token usage
  2. Set Tool Dependencies: Ensure proper execution order in xpander platform
  3. Optimize System Prompts: Keep instructions clear and concise
  4. Monitor Usage: Track API usage in both OpenAI and xpander dashboards

Whatโ€™s Next?

Now that you have a working LangChain + LangGraph integration:
  1. ๐Ÿ”ง Add More Tools: Explore xpanderโ€™s 2000+ tool library
  2. โš™๏ธ Configure Advanced Features: Set up output filtering and dependencies
  3. ๐Ÿ—๏ธ Build Complex Workflows: Create multi-step agent processes
  4. ๐Ÿ“Š Monitor Performance: Use xpanderโ€™s analytics dashboard
  5. ๐Ÿš€ Deploy to Production: Use xpanderโ€™s cloud infrastructure

Additional Resources

  • ๐Ÿ“š Documentation: docs.xpander.ai
  • ๐Ÿ’ฌ Discord Community: Join our Discord
  • ๐Ÿ› GitHub Issues: Report bugs and request features
  • โœ‰๏ธ Support: Contact support through the xpander platform

Ready to build production-grade AI agents with LangChain and xpander? Start building today ๐Ÿš€
โŒ˜I