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.
๐ 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.
Create a new Python file langchain_xpander_agent.py:
import osfrom dotenv import load_dotenvfrom langchain_openai import ChatOpenAIfrom langgraph.prebuilt import create_react_agentfrom langchain_core.messages import SystemMessagefrom xpander_sdk import Agents# Load environment variablesload_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()
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"]
# Example query that uses multiple toolscomplex_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) ]})
โ 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...
# Use different OpenAI modelsllm = ChatOpenAI(model="gpt-4o", temperature=0.7)# Or use other providers supported by LangChainfrom langchain_anthropic import ChatAnthropicllm = ChatAnthropic(model="claude-3-sonnet-20240229")