Tutorial Image: LangGraph Tutorial: Tool Configuration for Parallel Execution - Unit 2.3 Exercise 2

LangGraph Tutorial: Tool Configuration for Parallel Execution - Unit 2.3 Exercise 2

Learn how to configure tools for parallel execution in LangGraph, including real and mock tool setups, secure API key management, and testing with consistent settings for streamlined development and reliable functionality.

๐ŸŽฏ 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

  1. Tool Setup and Configuration
  2. Mock Tool Implementation
  3. Tool Call Structure
  4. 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

  1. Manages API keys securely
  2. Provides consistent settings
  3. Enables environment variable usage

Debug Tips

  1. 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

  1. Enable testing without API keys
  2. Provide consistent behavior
  3. 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

  1. Establishes proper credentials
  2. Enables API access
  3. 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

  1. Proper initialization
  2. Correct configuration
  3. 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

  1. Missing API key configuration
  2. Incorrect environment setup
  3. Invalid tool initialization
  4. Improper settings management

Key Takeaways

  1. Proper configuration is essential
  2. Mock tools enable testing
  3. Environment setup is critical
  4. Settings validation ensures reliability

Next Steps

  1. Add real API key
  2. Implement error handling
  3. Add more tool types
  4. 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()

Rod Rivera

๐Ÿ‡ฌ๐Ÿ‡ง Chapter