CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-langchain-cli

CLI for interacting with LangChain templates and applications

Pending
Overview
Eval results
Files

utilities.mddocs/

Utility Functions

Core utility functions for package management, git operations, project configuration, and event tracking used throughout the CLI. These utilities provide the foundational functionality that powers the CLI commands.

Capabilities

Package Management

Utilities for discovering and managing LangChain packages and their configurations.

def get_package_root(cwd: Optional[Path] = None) -> Path:
    """
    Get package root directory by traversing upward for pyproject.toml.
    
    Args:
        cwd: Starting directory (defaults to current directory)
        
    Returns:
        Path to directory containing pyproject.toml
        
    Raises:
        FileNotFoundError: If no pyproject.toml found in directory tree
    """

def get_langserve_export(filepath: Path) -> LangServeExport:
    """
    Get LangServe export information from a pyproject.toml file.
    
    Args:
        filepath: Path to pyproject.toml file
        
    Returns:
        LangServeExport with module, attr, and package_name
        
    Raises:
        KeyError: If invalid LangServe PyProject.toml format
    """

Usage Examples:

from langchain_cli.utils.packages import get_package_root, get_langserve_export

# Find project root
project_root = get_package_root()
print(f"Project root: {project_root}")

# Get LangServe export info
pyproject_path = project_root / "pyproject.toml"
export_info = get_langserve_export(pyproject_path)
print(f"Module: {export_info['module']}")
print(f"Attribute: {export_info['attr']}")
print(f"Package: {export_info['package_name']}")

Git Operations

Utilities for managing git repositories, dependency parsing, and template distribution.

def parse_dependency_string(
    dep: Optional[str],
    repo: Optional[str], 
    branch: Optional[str],
    api_path: Optional[str],
) -> DependencySource:
    """
    Parse a dependency string into a DependencySource.
    
    Args:
        dep: Dependency specification (template name or git URL)
        repo: GitHub repository override
        branch: Git branch/ref override  
        api_path: Custom API path for template
        
    Returns:
        DependencySource with git, ref, subdirectory, and metadata
        
    Raises:
        ValueError: If dependency format is invalid
    """

def parse_dependencies(
    dependencies: Optional[list[str]],
    repo: list[str],
    branch: list[str], 
    api_path: list[str],
) -> list[DependencySource]:
    """
    Parse multiple dependencies with parameter expansion.
    
    Args:
        dependencies: List of dependency strings
        repo: Repository specifications (expandable)
        branch: Branch specifications (expandable)
        api_path: API path specifications (expandable)
        
    Returns:
        List of DependencySource objects
        
    Raises:
        ValueError: If parameter lengths don't match
    """

def update_repo(gitstring: str, ref: Optional[str], repo_dir: Path) -> Path:
    """
    Update a git repository to the specified ref.
    
    Args:
        gitstring: Git repository URL
        ref: Git reference (branch, tag, commit)
        repo_dir: Directory for repository cache
        
    Returns:
        Path to updated repository
    """

def copy_repo(source: Path, destination: Path) -> None:
    """
    Copy a repository, ignoring git folders.
    
    Args:
        source: Source repository path
        destination: Destination path
        
    Raises:
        FileNotFoundError: If source doesn't exist
    """

Usage Examples:

from langchain_cli.utils.git import parse_dependencies, update_repo, copy_repo

# Parse template dependencies
deps = parse_dependencies(
    dependencies=["template1", "git+https://github.com/user/template.git"],
    repo=[],
    branch=["v0.2"],
    api_path=[],
)

# Update repository
repo_path = update_repo(
    "https://github.com/langchain-ai/langchain.git",
    "master", 
    Path("/tmp/repos")
)

# Copy template
copy_repo(repo_path / "templates/template1", Path("./packages/template1"))

Project Configuration

Utilities for managing pyproject.toml files and dependency configuration.

def add_dependencies_to_pyproject_toml(
    pyproject_toml: Path,
    local_editable_dependencies: Iterable[tuple[str, Path]],
) -> None:
    """
    Add editable dependencies to pyproject.toml.
    
    Args:
        pyproject_toml: Path to pyproject.toml file
        local_editable_dependencies: Iterable of (name, path) tuples
    """

def remove_dependencies_from_pyproject_toml(
    pyproject_toml: Path,
    local_editable_dependencies: Iterable[str],
) -> None:
    """
    Remove dependencies from pyproject.toml.
    
    Args:
        pyproject_toml: Path to pyproject.toml file  
        local_editable_dependencies: Iterable of dependency names
    """

Usage Examples:

from langchain_cli.utils.pyproject import add_dependencies_to_pyproject_toml, remove_dependencies_from_pyproject_toml

# Add local dependencies
add_dependencies_to_pyproject_toml(
    Path("pyproject.toml"),
    [("template1", Path("packages/template1")), ("template2", Path("packages/template2"))]
)

# Remove dependencies
remove_dependencies_from_pyproject_toml(
    Path("pyproject.toml"),
    ["template1", "template2"]
)

Event Tracking

Utilities for analytics and usage tracking.

def create_events(events: list[EventDict]) -> Optional[dict[str, Any]]:
    """
    Create analytics events.
    
    Args:
        events: List of event dictionaries
        
    Returns:
        Response data from analytics service or None on error
    """

Usage Examples:

from langchain_cli.utils.events import create_events

# Track CLI usage
events = [
    {
        "event": "template_added",
        "properties": {
            "template_name": "rag-template",
            "source": "github"
        }
    }
]

response = create_events(events)

Development Server Creation

Utilities for creating demo servers with different playground configurations for template development and testing.

def create_demo_server(
    *,
    config_keys: Sequence[str] = (),
    playground_type: Literal["default", "chat"] = "default"
) -> FastAPI:
    """
    Create a demo server for templates with configurable playground.
    
    Args:
        config_keys: Configuration keys to expose for dynamic configuration
        playground_type: Type of playground interface ("default" or "chat")
        
    Returns:
        FastAPI application instance configured for template serving
    """

def create_demo_server_configurable() -> FastAPI:
    """
    Create a demo server with configurable route for dynamic template parameters.
    
    Returns:
        FastAPI application with configurable endpoint
    """

def create_demo_server_chat() -> FastAPI:
    """
    Create a demo server with chat playground interface.
    
    Returns:
        FastAPI application with chat interface
    """

Usage Examples:

from langchain_cli.dev_scripts import create_demo_server, create_demo_server_configurable, create_demo_server_chat

# Create basic demo server
app = create_demo_server()

# Create server with configurable parameters
app_config = create_demo_server_configurable()

# Create server with chat interface  
app_chat = create_demo_server_chat()

# Create server with specific configuration keys
app_custom = create_demo_server(
    config_keys=["temperature", "model_name"],
    playground_type="chat"
)

GitHub Integration

Utilities for discovering and listing LangChain templates from GitHub repositories.

def list_packages(*, contains: Optional[str] = None) -> list[str]:
    """
    List available LangChain template packages from GitHub.
    
    Args:
        contains: Filter templates containing this substring
        
    Returns:
        List of template package names
        
    Raises:
        HTTPException: If GitHub API request fails
    """

Usage Examples:

from langchain_cli.utils.github import list_packages

# List all available templates
all_templates = list_packages()
print(f"Found {len(all_templates)} templates")

# Search for specific templates
rag_templates = list_packages(contains="rag")
print(f"RAG templates: {rag_templates}")

# Search for OpenAI templates
openai_templates = list_packages(contains="openai")
print(f"OpenAI templates: {openai_templates}")

Find and Replace

Utilities for template processing and string replacement operations across files and directories.

def find_and_replace(source: str, replacements: dict[str, str]) -> str:
    """
    Perform string replacements in source text.
    
    Args:
        source: Source text to process
        replacements: Dictionary of find->replace mappings
        
    Returns:
        Processed text with replacements applied
    """

def replace_file(source: Path, replacements: dict[str, str]) -> None:
    """
    Apply string replacements to a file in-place.
    
    Args:
        source: Path to file to modify
        replacements: Dictionary of find->replace mappings
        
    Raises:
        FileNotFoundError: If source file doesn't exist
        PermissionError: If file cannot be written
    """

def replace_glob(parent: Path, glob: str, replacements: dict[str, str]) -> None:
    """
    Apply string replacements to all files matching glob pattern.
    
    Args:
        parent: Parent directory to search
        glob: Glob pattern for file matching
        replacements: Dictionary of find->replace mappings
        
    Raises:
        FileNotFoundError: If parent directory doesn't exist
    """

Usage Examples:

from langchain_cli.utils.find_replace import find_and_replace, replace_file, replace_glob
from pathlib import Path

# Replace text in string
replacements = {
    "__package_name__": "my-integration",
    "__ModuleName__": "MyIntegration"
}

processed_text = find_and_replace("Template: __package_name__", replacements)
print(processed_text)  # "Template: my-integration"

# Replace in single file
replace_file(Path("template.py"), replacements)

# Replace in all Python files
replace_glob(Path("src/"), "**/*.py", replacements)

Additional Utilities

The CLI includes several other utility modules:

  • langchain_cli.constants: Configuration constants and defaults

Type Definitions

class LangServeExport(TypedDict):
    """Fields from pyproject.toml relevant to LangServe."""
    module: str      # Import module path
    attr: str        # Attribute to import  
    package_name: str # Package name

class DependencySource(TypedDict):
    """Dependency source information."""
    git: str                         # Git repository URL
    ref: Optional[str]               # Git reference (branch/tag/commit)
    subdirectory: Optional[str]      # Subdirectory within repository
    api_path: Optional[str]          # Custom API path
    event_metadata: dict[str, Any]   # Analytics metadata

class EventDict(TypedDict):
    """Event data structure for analytics tracking."""
    event: str                       # Event name
    properties: Optional[dict[str, Any]]  # Event properties

Configuration Constants

# Default repository settings
DEFAULT_GIT_REPO = "https://github.com/langchain-ai/langchain.git"
DEFAULT_GIT_SUBDIRECTORY = "templates"  
DEFAULT_GIT_REF = "master"

# Analytics configuration
WRITE_KEY = "310apTK0HUFl4AOv"  # Analytics write key

Error Handling

Common Error Patterns

  • FileNotFoundError: Missing pyproject.toml or template files
  • KeyError: Invalid LangServe configuration format
  • ValueError: Invalid dependency string formats or parameter mismatches
  • HTTPException: Network errors during git operations or analytics
  • OSError: File system permission or access issues

Error Recovery

Utilities include comprehensive error handling:

  • Graceful Degradation: Non-critical operations continue on errors
  • User Feedback: Clear error messages with actionable guidance
  • Retry Logic: Network operations include retry mechanisms
  • Validation: Input validation prevents common error conditions

Debugging Support

Enable detailed logging for troubleshooting:

import logging
logging.basicConfig(level=logging.DEBUG)

# Utilities will provide detailed debug information

Install with Tessl CLI

npx tessl i tessl/pypi-langchain-cli

docs

app-management.md

code-migration.md

index.md

integration-development.md

template-development.md

utilities.md

tile.json