Skip to main content

On This Page

Design Tool-Driven Agentic Workflows for Deterministic Route Optimization

3 min read
Share

These articles are AI-generated summaries. Please check the original sources for full details.

How to Design an Agentic Workflow for Tool-Driven Route Optimization with Deterministic Computation and Structured Outputs

The Route Optimizer Agent uses LangChain APIs to manage logistics dispatching through deterministic tool calls rather than LLM inference. It integrates the Haversine formula to ensure geographic calculations for sites like Rig_A and Yard_Main remain mathematically accurate.

Why This Matters

In production logistics, relying on an LLM’s internal reasoning for spatial or mathematical data leads to hallucinations and unreliable dispatching. By forcing the agent to use validated tools and structured Pydantic schemas, developers ensure that outputs are machine-readable and grounded in real-world physics. This approach bridges the gap between flexible natural language reasoning and the hard constraints of supply chain management, where minor errors in ETA can disrupt entire operations.

Key Insights

  • Deterministic tool-calling prevents LLM hallucinations in geographic calculations by using the Haversine formula with a 6371.0 km Earth radius.
  • Pydantic-enforced structured outputs, such as the RouteDecision model, ensure agent responses are directly consumable by downstream systems.
  • Configurable speed profiles including highway (90 km/h) and arterial (65 km/h) allow for realistic travel time modeling.
  • Multi-stop optimization logic evaluates waypoint permutations against specific objectives like ‘eta’ or ‘distance’.
  • The system prompt restricts the agent to ‘Return ONLY the structured RouteDecision’ to ensure reliability and minimize parsing errors.

Working Examples

Implementation of the Haversine formula for deterministic distance calculation between geographic coordinates.

from math import radians, sin, cos, sqrt, atan2

def haversine_km(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
    R = 6371.0
    dlat = radians(lat2 - lat1)
    dlon = radians(lon2 - lon1)
    a = sin(dlat / 2) ** 2 + cos(radians(lat1)) * cos(radians(lat2)) * sin(dlon / 2) ** 2
    c = 2 * atan2(sqrt(a), sqrt(1 - a))
    return R * c

A LangChain tool that allows the agent to compute and rank optimized routes based on distance or ETA.

@tool
def optimize_route(origin: str, destination: str, allowed_waypoints: Optional[List[str]] = None, max_stops: int = 2, road_class: str = "arterial", traffic_multiplier: float = 1.10, objective: str = "eta", top_k: int = 3) -> Dict[str, Any]:
    # Logic to find best route using candidate path generation and metric scoring
    return find_best_route(origin, destination, allowed_waypoints, int(max_stops), speed, float(traffic_multiplier), str(objective), int(top_k))

Pydantic schema and agent initialization to enforce structured, machine-readable output.

class RouteDecision(BaseModel):
    chosen: RoutePlan
    alternatives: List[RoutePlan] = []
    assumptions: Dict[str, Any] = {}
    notes: str = ""
    audit: List[str] = []

route_agent = create_agent(
    model=llm,
    tools=[list_sites, get_site_details, suggest_site, compute_direct_route, optimize_route],
    system_prompt=SYSTEM_PROMPT,
    response_format=RouteDecision,
)

Practical Applications

  • Logistics dispatch centers using LangChain agents to calculate optimal paths for rig-to-depot transfers based on real-world coordinates.
  • Pitfall: Allowing an LLM to guess distances without tool-calling, which leads to physically impossible routes and scheduling failures.
  • Fleet management platforms integrating real-time traffic buffers into deterministic travel time computations for multi-stop deliveries.
  • Pitfall: Using unstructured text responses that require brittle regex parsing instead of Pydantic-validated JSON schemas.

References:

Continue reading

Next article

Building a High-Performance yt-dlp Web Frontend for 1000+ Video Platforms

Related Content