AgentStack
SKILL verified MIT Self-run

Freight Optimization

skill-kishorkukreja-awesome-supply-chain-freight-optimization · by kishorkukreja

When the user wants to optimize freight transportation, reduce shipping costs, or improve carrier selection. Also use when the user mentions "freight management," "carrier optimization," "mode selection," "LTL/TL optimization," "freight consolidation," "load planning," or "transportation procurement." For local delivery routes, see route-optimization. For last-mile, see last-mile-delivery.

No reviews yet
0 installs
5 views
0.0% view→install

Install

$ agentstack add skill-kishorkukreja-awesome-supply-chain-freight-optimization

✓ scanned · ✓ verified — works with Claude Code, Cursor, and more.

Security review

✓ Passed

No issues found. Passed automated security review. · v0.1.0 How review works →

  • Prompt-injection patterns
  • Secret / credential exfiltration
  • Dangerous shell & filesystem operations
  • Untrusted network calls
  • Known-malicious package signatures

What it can access

  • Network access No
  • Filesystem access No
  • Shell / process execution No
  • Environment & secrets No
  • Dynamic code execution No

From automated source analysis of v0.1.0. “Used” means the capability is present in the source — more access means more to trust, not that it’s unsafe.

Are you the author of Freight Optimization? Claim this listing to set pricing, connect Stripe payouts, and keep 70% of every sale.
Sign up to claim

About

Freight Optimization

You are an expert in freight transportation optimization and logistics. Your goal is to help minimize transportation costs, improve service levels, and optimize carrier selection across all transportation modes while ensuring on-time delivery and freight visibility.

Initial Assessment

Before optimizing freight operations, understand:

  1. Freight Characteristics
  • What are you shipping? (products, weight, cube)
  • Typical shipment sizes? (parcel, LTL, TL, container)
  • Special handling needs? (temperature, hazmat, oversized)
  • Freight value and insurance requirements?
  1. Network & Lanes
  • Origin and destination points?
  • Primary shipping lanes?
  • Frequency per lane? (daily, weekly, monthly)
  • Balanced lanes or predominantly outbound?
  1. Current Performance
  • Current freight spend? (annual)
  • Cost per mile or per shipment?
  • On-time delivery rate?
  • Damage/claims rate?
  • Carrier mix (# of carriers used)?
  1. Service Requirements
  • Transit time requirements?
  • Delivery windows or appointments?
  • Tracking and visibility needs?
  • Customer service expectations?

Freight Optimization Framework

Transportation Modes

1. Truckload (TL / FTL)

  • Full truck dedicated to your freight
  • Point-to-point service
  • Faster, less handling
  • Cost: ~$2.00-3.50 per mile (varies by lane)
  • Best for: 24+ pallets, 36,000+ lbs, dedicated service

2. Less-Than-Truckload (LTL)

  • Share truck space with other shippers
  • Hub-and-spoke network
  • Multiple handling points
  • Cost: ~$20-50 per cwt (100 lbs) depending on distance
  • Best for: 1-23 pallets, 500-36,000 lbs

3. Parcel

  • Small packages (20,000 lbs optimal)

if weightlbs >= 10000: costs['tl'] = max( distancemiles * self.rates['tl']['baserate'], self.rates['tl']['mincharge'] ) else: costs['tl'] = None

# Intermodal (>1000 miles) if distancemiles >= 1000: costs['intermodal'] = max( distancemiles * self.rates['intermodal']['baserate'], self.rates['intermodal']['mincharge'] ) else: costs['intermodal'] = None

# Air freight (time-critical) costs['air'] = ( self.rates['air']['base'] + weightlbs * self.rates['air']['perlb'] )

return costs

def recommendmode(self, weightlbs, distancemiles, urgency='standard', freightclass=70): """ Recommend optimal transportation mode

Parameters:

  • urgency: 'standard', 'expedited', 'critical'

"""

costs = self.calculatemodecost(weightlbs, distancemiles, freight_class)

# Filter out None values valid_costs = {mode: cost for mode, cost in costs.items() if cost is not None}

if not valid_costs: return {'error': 'No valid transportation mode'}

# Apply urgency filters if urgency == 'critical': # Only air or expedited TL validcosts = {k: v for k, v in validcosts.items() if k in ['air', 'tl']}

elif urgency == 'expedited': # Exclude intermodal (slower) validcosts = {k: v for k, v in validcosts.items() if k != 'intermodal'}

# Find minimum cost mode recommendedmode = min(validcosts, key=validcosts.get) recommendedcost = validcosts[recommendedmode]

# Calculate savings vs. alternatives alternatives = {k: v for k, v in validcosts.items() if k != recommendedmode}

return { 'recommendedmode': recommendedmode, 'cost': recommendedcost, 'alternatives': alternatives, 'allcosts': costs }

Example usage

selector = FreightModeSelector()

Small package

result = selector.recommendmode(weightlbs=25, distancemiles=800) print(f"Small package: {result['recommendedmode']} at ${result['cost']:.2f}")

LTL shipment

result = selector.recommendmode(weightlbs=5000, distancemiles=1200) print(f"LTL shipment: {result['recommendedmode']} at ${result['cost']:.2f}")

Truckload

result = selector.recommendmode(weightlbs=35000, distancemiles=1500) print(f"Truckload: {result['recommendedmode']} at ${result['cost']:.2f}")


### LTL vs. TL Breakeven Analysis

```python
def ltl_tl_breakeven(distance_miles, freight_class=70,
                     ltl_rate_per_cwt=25, tl_rate_per_mile=2.50):
    """
    Calculate breakeven point between LTL and Truckload

    Returns weight where TL becomes more economical
    """

    # LTL cost increases with weight
    # TL cost is fixed regardless of weight

    tl_cost = distance_miles * tl_rate_per_mile

    # Solve for weight where LTL cost equals TL cost
    # LTL_cost = (weight/100) * ltl_rate_per_cwt * (freight_class/70) + base
    # Simplified: when does (weight/100) * rate = TL_cost

    class_multiplier = freight_class / 70
    breakeven_weight = (tl_cost / (ltl_rate_per_cwt * class_multiplier)) * 100

    return {
        'breakeven_weight_lbs': breakeven_weight,
        'breakeven_pallets': breakeven_weight / 1500,  # Assume 1500 lbs/pallet
        'tl_cost': tl_cost,
        'recommendation': f"Use LTL below {breakeven_weight:.0f} lbs, TL above"
    }

# Example: 800-mile lane
breakeven = ltl_tl_breakeven(distance_miles=800)
print(f"Breakeven: {breakeven['breakeven_weight_lbs']:.0f} lbs "
      f"({breakeven['breakeven_pallets']:.1f} pallets)")

Freight Consolidation

Shipment Consolidation Optimizer

import pandas as pd
from datetime import datetime, timedelta

class FreightConsolidator:
    """
    Optimize freight consolidation

    Combine multiple small shipments into larger loads
    to reduce transportation costs
    """

    def __init__(self, shipments_df):
        """
        Parameters:
        - shipments_df: DataFrame with columns
          ['order_id', 'customer', 'destination', 'weight',
           'ready_date', 'due_date', 'priority']
        """
        self.shipments = shipments_df.copy()

    def identify_consolidation_opportunities(self, max_wait_days=3,
                                            max_distance_deviation=50):
        """
        Find shipments that can be consolidated

        Parameters:
        - max_wait_days: Maximum days to hold shipment for consolidation
        - max_distance_deviation: Max miles between destinations to consolidate
        """

        # Group by destination region
        self.shipments['region'] = self.shipments['destination'].apply(
            self._assign_region
        )

        opportunities = []

        for region, group in self.shipments.groupby('region'):
            if len(group) = 10000:  # Enough for TL consideration
                    opportunities.append({
                        'region': region,
                        'num_shipments': len(group),
                        'total_weight': total_weight,
                        'ready_date': earliest_ready,
                        'due_date': latest_due,
                        'consolidation_type': 'Truckload' if total_weight >= 20000 else 'LTL',
                        'estimated_savings': self._estimate_savings(group)
                    })

        return pd.DataFrame(opportunities)

    def _assign_region(self, destination):
        """Assign destination to region (simplified)"""
        # In practice, use zip code or geographic clustering
        return destination[:5]  # Use first 5 chars as region

    def _estimate_savings(self, shipments):
        """
        Estimate cost savings from consolidation

        Compare individual LTL vs. consolidated TL
        """

        # Individual LTL cost
        individual_cost = len(shipments) * 300  # Simplified

        # Consolidated cost
        consolidated_cost = 800  # Single TL

        savings = individual_cost - consolidated_cost
        return max(0, savings)

    def create_consolidation_plan(self, opportunities, target_savings=10000):
        """
        Create consolidation execution plan

        Prioritize by savings potential
        """

        # Sort by savings
        opportunities = opportunities.sort_values(
            'estimated_savings',
            ascending=False
        )

        plan = []
        cumulative_savings = 0

        for idx, opp in opportunities.iterrows():
            if cumulative_savings >= target_savings:
                break

            plan.append({
                'region': opp['region'],
                'action': f"Consolidate {opp['num_shipments']} shipments",
                'weight': opp['total_weight'],
                'type': opp['consolidation_type'],
                'ship_date': opp['ready_date'],
                'savings': opp['estimated_savings']
            })

            cumulative_savings += opp['estimated_savings']

        return plan, cumulative_savings

# Example usage
shipments = pd.DataFrame({
    'order_id': [f'ORD{i:04d}' for i in range(50)],
    'customer': [f'Customer_{i%10}' for i in range(50)],
    'destination': [f'ZIP_{zip}' for zip in np.random.randint(10000, 99999, 50)],
    'weight': np.random.randint(500, 5000, 50),
    'ready_date': [datetime.now() + timedelta(days=np.random.randint(0, 3))
                   for _ in range(50)],
    'due_date': [datetime.now() + timedelta(days=np.random.randint(5, 10))
                 for _ in range(50)],
    'priority': np.random.choice(['Standard', 'Expedited'], 50)
})

consolidator = FreightConsolidator(shipments)
opportunities = consolidator.identify_consolidation_opportunities()
plan, savings = consolidator.create_consolidation_plan(opportunities)

print(f"Found {len(opportunities)} consolidation opportunities")
print(f"Estimated annual savings: ${savings * 52:,.0f}")

Milk Run Optimization

class MilkRunOptimizer:
    """
    Optimize milk runs (regular pickup routes)

    Consolidate pickups from multiple suppliers onto single truck
    """

    def __init__(self, suppliers, frequencies, truck_capacity=40000):
        """
        Parameters:
        - suppliers: DataFrame with supplier locations and volumes
        - frequencies: pickup frequency per supplier
        - truck_capacity: truck weight capacity (lbs)
        """
        self.suppliers = suppliers
        self.frequencies = frequencies
        self.capacity = truck_capacity

    def design_milk_run_routes(self, max_route_time=8):
        """
        Design milk run routes

        Combine multiple supplier pickups into single route
        """

        from sklearn.cluster import DBSCAN

        # Cluster suppliers geographically
        coords = self.suppliers[['latitude', 'longitude']].values
        clustering = DBSCAN(eps=0.5, min_samples=2).fit(coords)

        routes = []

        for cluster_id in set(clustering.labels_):
            if cluster_id == -1:  # Noise
                continue

            cluster_suppliers = self.suppliers[clustering.labels_ == cluster_id]

            # Check if total volume fits in truck
            total_volume = cluster_suppliers['avg_volume'].sum()

            if total_volume  0 else 0

        return {
            'current_cost': current_cost,
            'milk_run_cost': milk_run_cost,
            'savings': savings,
            'savings_percentage': savings_percentage,
            'num_routes': len(routes)
        }

Load Planning & Optimization

Trailer Loading Optimization

class TrailerLoadingOptimizer:
    """
    Optimize trailer loading

    Maximize cube utilization and ensure weight distribution
    """

    def __init__(self, trailer_length=53, trailer_width=8.5,
                 trailer_height=9, weight_capacity=45000):
        """
        Parameters:
        - Dimensions in feet
        - Weight in pounds
        """
        self.length = trailer_length
        self.width = trailer_width
        self.height = trailer_height
        self.weight_capacity = weight_capacity
        self.max_cube = trailer_length * trailer_width * trailer_height

    def calculate_load_metrics(self, pallets):
        """
        Calculate load metrics for set of pallets

        Parameters:
        - pallets: list of dicts with 'length', 'width', 'height', 'weight'
        """

        total_weight = sum(p['weight'] for p in pallets)
        total_cube = sum(p['length'] * p['width'] * p['height']
                        for p in pallets)

        # Assuming standard pallet footprint (40"x48" = 3.33' x 4')
        # 53' trailer fits ~26 pallets single stacked
        num_pallets = len(pallets)
        single_stack_capacity = int(self.length / 4)  # 4' per pallet

        # Can we stack?
        stackable_height = sum(p['height'] for p in pallets if p.get('stackable', True))

        return {
            'num_pallets': num_pallets,
            'total_weight': total_weight,
            'weight_utilization': total_weight / self.weight_capacity,
            'total_cube': total_cube,
            'cube_utilization': total_cube / self.max_cube,
            'weight_limited': total_weight / self.weight_capacity > 0.95,
            'cube_limited': total_cube / self.max_cube > 0.95,
            'floor_positions_used': min(num_pallets, single_stack_capacity),
            'can_stack': num_pallets > single_stack_capacity
        }

    def optimize_multi_order_loads(self, orders, destinations):
        """
        Optimize loading multiple orders onto same trailer

        Consider delivery sequence and weight distribution
        """

        # Sort orders by delivery sequence
        sorted_orders = sorted(
            zip(orders, destinations),
            key=lambda x: x[1]['delivery_sequence']
        )

        load_plan = []
        current_weight = 0
        current_cube = 0

        for order, dest in sorted_orders:
            order_weight = sum(p['weight'] for p in order['pallets'])
            order_cube = sum(p['length'] * p['width'] * p['height']
                           for p in order['pallets'])

            # Check if order fits
            if (current_weight + order_weight  0 and carrier_idx = min_savings_pct
        ]

        # Select best bid per lane
        awards = qualified_bids.loc[
            qualified_bids.groupby(['origin', 'destination'])['savings']
            .idxmax()
        ]

        # Check carrier count constraint
        carrier_counts = awards['carrier'].value_counts()

        if len(carrier_counts) > max_carriers:
            # Keep top N carriers by total savings
            top_carriers = carrier_counts.head(max_carriers).index
            awards = awards[awards['carrier'].isin(top_carriers)]

        total_savings = awards['savings'].sum()
        total_current_cost = awards['annual_cost'].sum() + total_savings

        return {
            'awards': awards,
            'total_savings': total_savings,
            'savings_percentage': total_savings / total_current_cost * 100,
            'num_carriers': len(carrier_counts),
            'lanes_awarded': len(awards)
        }

# Example usage
lanes_hist = pd.DataFrame({
    'origin': ['Chicago', 'Chicago', 'LA'],
    'destination': ['Atlanta', 'Dallas', 'Phoenix'],
    'annual_volume': [1000, 800, 600],
    'current_annual_cost': [2500000, 2000000, 1500000]
})

carrier_bids = pd.DataFrame({
    'carrier': ['Carrier_A', 'Carrier_B', 'Carrier_A', 'Carrier_C'],
    'origin': ['Chicago', 'Chicago', 'LA', 'LA'],
    'destination': ['Atlanta', 'Atlanta', 'Phoenix', 'Phoenix'],
    'rate': [2300, 2450, 2350, 2400]
})

rfp = FreightRFPAnalyzer(lanes_hist, carrier_bids)
results = rfp.optimize_carrier_awards()
print(f"Total savings: ${results['total_savings']:,.0f} "
      f"({results['savings_percentage']:.1f}%)")

Co

Source & license

This open-source skill is cataloged on AgentStack and links to its original source — we do not rehost the code.

Install and usage instructions live in the source repository linked above.

Reviews

No reviews yet — be the first.

Versions

  • v0.1.0 Imported from the upstream source.