Digital Employee for Supply Chain: AI Logistics Agent

We design and deploy artificial intelligence systems: from prototype to production-ready solutions. Our team combines expertise in machine learning, data engineering and MLOps to make AI work not in the lab, but in real business.
Showing 1 of 1All 1564 services
Digital Employee for Supply Chain: AI Logistics Agent
Complex
from 2 weeks to 3 months
Frequently Asked Questions

AI Development Areas

AI Solution Development Stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1357
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1250
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    956
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1188
  • image_logo-advance_0.webp
    B2B Advance company logo design
    646
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    929

AI Logistics Agent: Digital Employee for Supply Chain Automation

Logistics companies spend up to 70% of operator time on shipment monitoring and exception handling. With 100 shipments per day, an operator manually checks statuses 5–10 times, taking up to 4 hours. Each delay reduces customer loyalty and increases penalties. We developed an AI agent that automates supply chain operational tasks: route planning, shipment tracking, carrier communication, exception handling (delays, damage, shortages), KPI monitoring, and report generation. A human operator steps in only for non-standard situations requiring negotiation. The result — manual labor reduced by 55% and on-time delivery increased to 89%. Average annual cost savings: 2,500,000 rubles for 500 shipments/day.

How the AI Agent Reduces the Load on Logisticians?

The agent works in three stages: data collection, analysis via LLM, and automatic action execution. For tracking, it connects to carrier APIs (DPD, CDEK, PEC, etc.) every 2 hours and compares actual status with expected. When a delay is detected, the system calculates downtime and decides: notify the recipient, rebook delivery, or escalate to a manager. On average, the agent processes an exception 3 times faster than a human.

from langgraph.graph import StateGraph, END
from langchain_openai import ChatOpenAI
from typing import TypedDict, Annotated, Optional
import operator

llm = ChatOpenAI(model="gpt-4o", temperature=0)

class ShipmentState(TypedDict):
    shipment_id: str
    shipment_data: dict
    tracking_history: list[dict]
    anomalies: Annotated[list, operator.add]
    actions_taken: Annotated[list, operator.add]
    escalation_required: bool
    escalation_reason: Optional[str]

class ShipmentMonitor:

    async def check_shipment(self, shipment_id: str) -> ShipmentState:
        """Full shipment status check"""
        
        # Get data
        shipment = await logistics_db.get_shipment(shipment_id)
        tracking = await carrier_api.get_tracking(shipment["tracking_number"])
        expected_eta = shipment["expected_delivery"]
        current_eta = tracking.get("estimated_delivery")

        anomalies = []

        # Check delay
        if current_eta and current_eta > expected_eta:
            delay_hours = (current_eta - expected_eta).total_seconds() / 3600
            anomalies.append({
                "type": "delivery_delay",
                "severity": "high" if delay_hours > 24 else "medium",
                "details": f"Delay {delay_hours:.0f} hours, new date: {current_eta}",
            })

        # No updates
        last_update = tracking.get("last_event_time")
        hours_since_update = (datetime.now() - last_update).total_seconds() / 3600 if last_update else 99
        if hours_since_update > 48:
            anomalies.append({
                "type": "no_tracking_update",
                "severity": "medium",
                "details": f"No updates {hours_since_update:.0f} hours",
            })

        # LLM analysis for anomalies
        escalation_required = False
        escalation_reason = None

        if anomalies:
            assessment = await self.assess_anomalies(shipment, anomalies)
            escalation_required = assessment["requires_escalation"]
            escalation_reason = assessment.get("reason")

        return ShipmentState(
            shipment_id=shipment_id,
            shipment_data=shipment,
            tracking_history=tracking.get("events", []),
            anomalies=anomalies,
            actions_taken=[],
            escalation_required=escalation_required,
            escalation_reason=escalation_reason,
        )

    async def assess_anomalies(self, shipment: dict, anomalies: list) -> dict:
        """LLM assesses whether escalation is needed"""

        response = await llm.ainvoke(f"""Assess the shipment situation.
Shipment: {json.dumps(shipment, ensure_ascii=False)}
Anomalies: {json.dumps(anomalies, ensure_ascii=False)}

Determine:
1. Does the situation require immediate escalation to manager?
2. What automatic actions can be taken?
3. Should the recipient be notified?

Return JSON: {{"requires_escalation": bool, "reason": "...", "auto_actions": [...], "notify_recipient": bool}}""")

        return json.loads(response.content)

Routing uses a hybrid approach: for small problems (up to 20 points) — LLM with chain-of-thought, for large ones — an algorithmic solver with AI post-processing. This yields optimal routes accounting for time windows, load capacity, and traffic. Learn more about Vehicle Routing Problem.

class RouteOptimizer:

    async def optimize_delivery_routes(
        self,
        deliveries: list[dict],    # [{id, address, time_window, weight}]
        vehicles: list[dict],      # [{id, capacity, location}]
        date: str,
    ) -> dict:
        """Optimize delivery routes (Vehicle Routing Problem)"""

        # For small tasks — via LLM with reasoning
        if len(deliveries) <= 20:
            return await self.llm_route_optimizer(deliveries, vehicles)

        # For large — algorithmic approach + LLM for exceptions
        return await self.algorithmic_route_optimizer(deliveries, vehicles)

    async def llm_route_optimizer(self, deliveries: list, vehicles: list) -> dict:
        response = await llm.ainvoke(f"""Compose optimal delivery routes.
Deliveries:
{json.dumps(deliveries, ensure_ascii=False, indent=2)}

Vehicles:
{json.dumps(vehicles, ensure_ascii=False, indent=2)}

Consider: time windows, load capacity, minimize total distance.
Return JSON: {{"routes": [{{"vehicle_id": "...", "stops": [delivery_ids_in_order]}}]}}""")

        return json.loads(response.content)

Exception handling is built on playbooks — predefined scenarios for typical situations: delay, damage, customs hold, incorrect address. The agent performs automatic actions (notifications, claim creation, rebooking) and escalates only when automation is insufficient.

class ExceptionHandler:

    EXCEPTION_PLAYBOOKS = {
        "delivery_delay": {
            "auto_actions": ["notify_recipient", "update_crm", "rebook_if_urgent"],
            "escalate_if": lambda hours: hours > 72,
        },
        "damaged_goods": {
            "auto_actions": ["create_claim", "notify_sender", "photo_request"],
            "escalate_always": True,
        },
        "customs_hold": {
            "auto_actions": ["get_customs_details", "notify_broker"],
            "escalate_if": lambda days: days > 3,
        },
        "address_not_found": {
            "auto_actions": ["contact_recipient", "check_database"],
            "escalate_if": lambda attempts: attempts > 2,
        },
    }

    async def handle_exception(self, exception: dict) -> dict:
        exception_type = exception["type"]
        playbook = self.EXCEPTION_PLAYBOOKS.get(exception_type)

        if not playbook:
            return await self.generic_exception_handler(exception)

        actions_taken = []

        # Execute automatic actions
        for action in playbook.get("auto_actions", []):
            result = await self.execute_action(action, exception)
            actions_taken.append({"action": action, "result": result})

        # Check if escalation needed
        escalate = playbook.get("escalate_always", False)
        if not escalate and "escalate_if" in playbook:
            escalate_fn = playbook["escalate_if"]
            escalate = escalate_fn(exception.get("delay_hours") or exception.get("hold_days") or exception.get("attempts", 0))

        if escalate:
            await self.escalate_to_manager(exception, actions_taken)

        return {"actions_taken": actions_taken, "escalated": escalate}

The analytics module daily collects key metrics and generates a KPI report in natural language. The report includes deviations from norms and recommendations for improvement.

class LogisticsAnalytics:

    async def daily_kpi_report(self) -> str:
        """Daily KPI report for logistics"""

        # Data from DB
        metrics = await asyncio.gather(
            self.get_on_time_delivery_rate(),
            self.get_damage_rate(),
            self.get_carrier_performance(),
            self.get_cost_per_shipment(),
            self.get_exception_rate(),
        )

        report = await llm.ainvoke(f"""Create a KPI report for logistics for {datetime.now().strftime('%d.%m.%Y')}.

Metrics:
- On-time delivery: {metrics[0]['rate']:.1%} (target: {metrics[0]['target']:.1%})
- Damage rate: {metrics[1]['rate']:.3%}
- Top carriers by performance: {metrics[2]}
- Cost per shipment: {metrics[3]['avg']:,.0f} rub
- Exception rate: {metrics[4]['rate']:.2%}

Format: brief summary (3 sentences), deviations from norms, recommendations.""")

        return report.content

What Does Hybrid Routing Offer?

The hybrid approach allows processing up to 500 delivery points per minute, combining algorithmic speed with LLM flexibility. For standard routes with time windows, an algorithmic optimizer is used; for non-standard requests (urgent delivery, priority changes), the LLM with reasoning is engaged. This reduces average routing time by 40% compared to a purely algorithmic approach.

Implementation Results: 55% Reduction in Manual Labor

Metric Without AI With AI Improvement
Manual exception handling 180 cases/day 45 cases/day -75%
On-time delivery rate 82% 89% +7 p.p.
Correct claim processing 62% 91% +29 p.p.
Time on operational work 100% 45% -55%
Average annual cost savings 2,500,000 rubles

Exception handling time comparison:

Exception type Human (min) AI agent (sec) Speedup
Delivery delay 12 45 16x
Goods damage 25 120 12.5x
Customs hold 30 90 20x
Incorrect address 8 30 16x

These numbers come from our practical case with an FMCG distributor handling 500 shipments per day. Our specialists have extensive experience integrating AI solutions into logistics, use proven stacks (LangGraph, OpenAI GPT-4o, ChromaDB), and provide a guarantee for each stage. Implementation can reduce operational costs by several million rubles annually for a company with a volume of 200+ shipments per day. Savings on operational expenses — from 2,000,000 to 3,000,000 rubles per year at a volume of 500 shipments.

Implementation Stages

  1. Audit of current processes and integrations — 1 week.
  2. Connection to carrier and warehouse APIs — 1–2 weeks.
  3. Development of tracking module and exception playbooks — 2–3 weeks.
  4. Configuration of routing and KPI analytics — 2–3 weeks.
  5. Testing on historical data and pilot launch — 1–2 weeks.
  6. Full launch and operator training — 1 week.

Total timeline: 8–12 weeks depending on the number of carriers and exception complexity.

Deliverables

  • A working AI agent in your infrastructure (on-prem or cloud).
  • Integration with 3–5 carriers (expandable upon request).
  • Playbook for 5+ exception types (customizable).
  • Daily KPI report in natural language.
  • Documentation and operator team training.
  • Access to agent dashboard and support for 30 days after launch.

Agent architecture: LangGraph for workflow orchestration, GPT-4o for natural language understanding, ChromaDB for vector retrieval. This stack ensures scalability and rapid response times.

We guarantee a minimum 50% reduction in manual exception handling. Payback period — from 6 months at a volume of 200+ shipments per day.

Our Expertise

Our team has 10+ years of experience in logistics and 5+ years in AI implementation, with over 50 successful projects across industries. We combine deep domain knowledge with cutting-edge AI to deliver measurable results.

To assess the applicability of the AI agent in your processes, contact us. Get a consultation on implementation — we will analyze your logistics processes and offer an optimal turnkey solution.

LLM Development: Fine-Tuning, RAG, Agents, and Production Deployment

Using GPT‑4 or Claude 3.5 Sonnet through a public API is not a solution — it's just a tool. When the requirement is to "make it like ChatGPT, but on our data," there is a real engineering challenge behind it: from prompt engineering to training a 70B model on your own infrastructure. End-to-end LLM solution development is a complex stack, and we have been doing it for over 5 years. During this time, we have completed over 20 projects in generative AI: from RAG systems for legal departments to custom support agents. Where exactly your task falls depends on data, latency requirements, budget, and how critical confidentiality is.

A typical situation: the client has already tried ChatGPT, but results are unstable — sometimes accurate, sometimes hallucinating. Or they need integration into a corporate portal while complying with security policies. Let's break down each layer of the stack in detail — from RAG to production deployment.

Why Do RAG Systems Break and How to Fix It?

RAG (Retrieval-Augmented Generation) looks simple: find relevant documents, put them in context, get an answer. In practice, it fails in several places.

Chunking without overlap. Classic mistake: chunk_size=512, overlap=0. If the answer lies across two chunks, retrieval won't find either with sufficient confidence. Solution: overlap 15–25% of chunk_size, or better yet, sentence-aware splitting with spaCy or NLTK instead of naive character splitting.

Poor embedder. text-embedding-ada-002 is good for general use, but on legal or medical texts, specialized models like E5-large-v2, BGE-M3, or fine-tuned sentence-transformers on domain data outperform it. Recall@5 differences can be 15–25%.

No re-ranking. Vector search optimizes for speed, not relevance. A cross-encoder re-ranker (ms-marco-MiniLM-L-6-v2, bge-reranker-large) after initial retrieval improves top-3 accuracy with acceptable latency (+50–150ms). This is often more impactful than improving the embedding model.

Hybrid search. Dense vectors alone work poorly on exact queries: names, SKUs, codes. BM25 (sparse) finds exact matches but misses semantics. Hybrid via RRF (Reciprocal Rank Fusion) is the optimal compromise. Qdrant, Weaviate, and pgvector 0.7+ support hybrid search natively.

Typical production architecture for a corporate knowledge base
  1. Documents → preprocessing (PyMuPDF, Unstructured)
  2. Chunking → embedding (BGE-M3)
  3. Qdrant (hybrid dense+sparse)
  4. Cross-encoder re-ranking
  5. Context → LLM (vLLM or OpenAI API)
  6. Answer with sources (RAGAS for quality evaluation)

When to Fine-Tune Instead of Prompt Engineering?

Prompt engineering solves ~70% of LLM adaptation tasks for a domain. The remaining 30% require fine-tuning. Three indicators: the model ignores a specific output format even with detailed prompting; the task requires deep knowledge of specialized vocabulary (medicine, law); you need to significantly reduce token costs by replacing a large model with a smaller specialized one.

LoRA and QLoRA are the standard for SFT. LoRA adds trainable low-rank matrices to attention layers. A typical configuration for Llama-3 8B: r=64, lora_alpha=128, target_modules=["q_proj","v_proj","k_proj","o_proj"] yields ~0.8% trainable parameters, training on one A100 40GB. QLoRA adds 4-bit quantization (NF4) and allows fine-tuning 70B models on two A100 40GB, though speed drops by half compared to bf16.

DPO instead of RLHF. Direct Preference Optimization requires only (chosen, rejected) pairs, not scalar reward signals. DPOTrainer from the trl library (Hugging Face) implements it in a few dozen lines.

Common mistake. A dataset of 500 examples, 5 epochs, validation loss 0.8 — seems fine. But on test, the model degrades on general instructions. Cause: catastrophic forgetting. Solution: add 10–20% general instruction-following examples (Alpaca, FLAN) to the training set to preserve original capabilities.

How to Choose a Base Model: 8B or 70B?

Model Parameters Strengths Context
Llama-3.1 8B 8B Quality/speed balance 128k
Llama-3.1 70B 70B Complex reasoning 128k
Mistral 7B / Mixtral 8x7B 7B / 47B Efficiency for size 32k
Qwen2.5 72B 72B Code, multilingual 128k
Gemma 2 27B 27B Open license 8k

For most tasks, fine-tuning an 8B model is sufficient. 70B is needed when deep reasoning is required or the 8B baseline does not reach the required quality even after fine-tuning. Inference cost for Llama-3 8B via vLLM on A100 is efficient; the exact cost depends on volume.

What Does PagedAttention Bring to Production?

vLLM is the first choice for serving open-source models. PagedAttention is the key technical innovation: KV-cache is managed like virtual memory in an OS, without fragmentation. This yields 2–4x higher throughput compared to naive HuggingFace Transformers inference. The vLLM documentation confirms that continuous batching and PagedAttention are the standard for high-load LLM services.

Typical numbers on A100 80GB for Llama-3 8B (bf16): 400–600 req/s, P50 latency 200–400ms, P99 latency 600–900ms at concurrency 64. For 70B on two A100 with tensor parallelism: 80–120 req/s, P99 latency 1.5–2.5s. AWQ or GPTQ quantization reduces memory consumption by 2x with quality loss within 1–3%.

Multi-Agent Systems

Agents are LLMs with access to tools: search, code execution, API calls, database interaction. Common patterns:

  • ReAct (Reason + Act): the model reasons → chooses a tool → observes the result → reasons again. LangChain and LlamaIndex implement it out of the box.
  • Multi-agent orchestration: multiple specialized agents with a coordinator on top. Example: coordinator → researcher (search + summarization) → coder (code generation and execution) → critic (verification). Tools: AutoGen (Microsoft), CrewAI, custom implementation on LangGraph.

In production, agent systems are non-deterministic. Essential: guardrails, step limits, logging of each step, human-in-the-loop for critical actions.

How We Work: Stages, Timeline, Deliverables

Stage Duration What You Get
Audit and data collection 1–2 weeks Eval dataset of 100+ examples, task formalization
Baseline (prompt + RAG) 1–2 weeks Working prototype, quality metrics
Fine-tuning (if needed) 2–4 weeks Trained model, LoRA weights, model card
Deployment and monitoring 1–2 weeks vLLM server, Grafana + Prometheus
Documentation and training 1 week API documentation, team training

What Is Included

We deliver:

  • Technical documentation (model card, configs, deployment instructions)
  • Access to infrastructure (code repository, trained weights)
  • 1 month of post-deployment support (consultations, bug fixes)
  • Customer team training (2–3 sessions on system operation)

Timeline: basic RAG prototype — 1–2 weeks. Fine-tuning with customer data — 3–6 weeks (including data preparation). Production system with monitoring and retraining — 2–4 months. Cost is calculated individually based on data volume, model complexity, and infrastructure requirements.

We guarantee the quality of the final model with performance benchmarks and ongoing monitoring. Our engineers have hands‑on experience with dozens of production LLM systems.

Want to evaluate your project? Leave a request — we will prepare a preliminary summary within 1–2 business days. Or get a consultation on choosing the approach: RAG, fine-tuning, or hybrid — we will tell you what works best for you. Contact us to discuss your LLM development needs. Schedule a free consultation today.