๐ฏ What You'll Learn Today
LangGraph Tutorial: Tool Configuration for Parallel Execution - Unit 2.3 Exercise 2
This tutorial is also available in Google Colab here or for download here
Joint Initiative: This tutorial is part of a collaboration between AI Product Engineer and the Nebius Academy.
This tutorial demonstrates how to configure and initialize tools for parallel execution in LangGraph, including both real and mock tools for testing.
Key Concepts Covered
- Tool Setup and Configuration
- Mock Tool Implementation
- Tool Call Structure
- Testing Patterns
import os
!pip install langchain-core
!pip install langgraph
!pip install langchain-community
from langchain_community.tools import TavilySearchResults
from langchain_core.messages import AIMessage
from pydantic_settings import BaseSettings
Step 1: Configuration Management
Set up configuration using Pydantic BaseSettings.
Why This Matters
Proper configuration is crucial because
- Manages API keys securely
- Provides consistent settings
- Enables environment variable usage
Debug Tips
-
Configuration Issues:
- Check environment variables
- Verify API key format
- Monitor settings loading
MOCK_TAVILY_KEY = "mock_tavily_api_key_12345"
class Settings(BaseSettings):
"""Configuration for tool setup.
Notes:
- Uses Pydantic for validation
- Provides mock key default
- Enables environment override
"""
tavily_api_key: str = MOCK_TAVILY_KEY
Step 2: Mock Tool Implementation
Create mock tool for testing parallel execution.
Why This Matters
Mock tools are essential because
- Enable testing without API keys
- Provide consistent behavior
- Speed up development
def mock_tool(query: str = "mock query") -> dict:
"""Mock tool for parallel execution testing.
Args:
query: Test query string
Returns:
dict: Structured response matching real tool
"""
message = AIMessage(content=f"Mock tool called with query: {query}")
return {"messages": [message], "results": {"mock_tool": "mock_value"}, "errors": {}}
Step 3: Tool Configuration
Configure real and mock tools with proper settings.
Why This Matters
Tool configuration is crucial because
- Establishes proper credentials
- Enables API access
- Manages tool state
def setup_tool_environment():
"""Set up the tool environment with proper configuration.
Returns:
tuple: Settings, tool instance, and tool calls
"""
# Initialize settings
settings = Settings()
# Set up environment
os.environ["TAVILY_API_KEY"] = settings.tavily_api_key
# Initialize tool
tavily_tool = TavilySearchResults()
# Create tool calls
real_tool_call = {
"id": "search_1",
"tool_name": "TavilySearchResults",
"args": {"query": "capital of France"},
}
mock_tool_call = {
"id": "mock_1",
"tool_name": "mock_tool",
"args": {"query": "test query"},
}
return settings, tavily_tool, (real_tool_call, mock_tool_call)
Step 4: System Demonstration
Test the tool configuration system.
Why This Matters
Testing verifies
- Proper initialization
- Correct configuration
- Tool functionality
def demonstrate_tool_configuration():
"""Demonstrate tool configuration and testing."""
print("Tool Configuration Demonstration")
print("==============================")
# Set up environment
settings, tool, (real_call, mock_call) = setup_tool_environment()
# Test mock tool
print("\nMock Tool Test:")
mock_result = mock_tool("test query")
print(f"Query: {mock_call['args']['query']}")
print(f"Result: {mock_result['results']}")
print(f"Messages: {mock_result['messages'][0].content}")
# Show real tool configuration
print("\nReal Tool Configuration:")
print(f"API Key Configured: {bool(settings.tavily_api_key)}")
print(f"Tool Name: {real_call['tool_name']}")
print(f"Arguments: {real_call['args']}")
return settings, tool, mock_result
Common Pitfalls
- Missing API key configuration
- Incorrect environment setup
- Invalid tool initialization
- Improper settings management
Key Takeaways
- Proper configuration is essential
- Mock tools enable testing
- Environment setup is critical
- Settings validation ensures reliability
Next Steps
- Add real API key
- Implement error handling
- Add more tool types
- Enhance configuration options
Expected Output
Tool Configuration Demonstration
## Mock Tool Test
Query: test query
Result: {'mock_tool': 'mock_value'}
Messages: Mock tool called with query: test query
## Real Tool Configuration
API Key Configured: True
Tool Name: TavilySearchResults
Arguments: {'query': 'capital of France'}
if __name__ == "__main__":
demonstrate_tool_configuration()
๐ฌ๐ง Chapter