Skip to content

Logistic-System/bookr

Repository files navigation

Bookr - Logistics Booking Agent

Bookr is a no-nonsense logistics and supply chain orchestrator built on the ElizaOS framework. Currently, Bookr ONLY handles ocean container shipments (FCL/LCL) between China and the European Union. Bookr provides conversational access to shipping quotes, rate comparison, vessel schedules, and freight booking capabilities through natural language interactions with a pragmatic, decisive, and solution-oriented approach.

Features

🚢 Booking & Quoting

  • Intelligent Quote Fetching: Get shipping quotes from multiple carriers for China-EU ocean container routes
  • Deterministic Ranking: Transparent scoring algorithm based on price, transit time, and CO₂ emissions
  • User Preferences: Configurable weight preferences (Low/Medium/High) for ranking customization
  • Ocean Container Focus: Specialized in FCL and LCL shipments between China and the European Union

🌐 SeaRates Integration

  • Real-Time Quotes: Automatic integration with DPWorld SeaRates Logistics Explorer API
  • Smart Caching: Database-first approach with automatic refresh for stale quotes (>24 hours)
  • Rate Limiting: Built-in tracking to prevent API limit exceedance
  • Carrier Auto-Discovery: Automatically creates carrier entries from API responses

📦 APM Terminals

  • Vessel Schedules: Query vessel schedules for APM terminals worldwide
  • Smart Scoring: Intelligent ranking of schedules by relevance and timeliness
  • Terminal Detection: Automatic terminal code detection from natural language queries

🤖 Chat-Based Interface

  • Natural Language Processing: Interact with the agent using conversational commands
  • Action Recognition: Automatic detection of booking, quoting, and scheduling requests
  • Context Awareness: Maintains conversation context for multi-step workflows
  • Operational Focus: Pragmatic, decisive responses with structured checklists, timelines, and concise quotes
  • Scope Management: Automatically declines requests outside China-EU ocean container shipments

Getting Started

Prerequisites

  • Node.js 18+ or Bun runtime
  • PostgreSQL database
  • API keys for external services (optional, for full functionality)

Installation

# Clone the repository
git clone https://github.com/Logistic-System/bookr
cd bookr

# Install dependencies
bun install

# Build the project
bun run build

Configuration

Create a .env file in the project root with the following variables:

# Database (required)
DATABASE_URL=postgresql://user:password@localhost:5432/bookr

# LLM Provider (at least one required)
OPENAI_API_KEY=your_openai_key
# OR
ANTHROPIC_API_KEY=your_anthropic_key
# OR
OLLAMA_API_ENDPOINT=http://localhost:11434

# SeaRates API (optional, for real-time quotes)
SEARATES_API_KEY=K-8B728F90-8963-41EB-B3C4-3011D4C5D326
SEARATES_PLATFORM_ID=32322

# APM Terminals (optional, for vessel schedules)
APM_TERMINALS_CONSUMER_KEY=your_consumer_key
APM_TERMINALS_CONSUMER_SECRET=your_consumer_secret

Database Setup

  1. Create the database:
createdb bookr
  1. Run migrations:
# Create database schema
psql -d bookr -f migrations/001_initial_schema.sql

# Seed common locations and carriers (recommended)
psql -d bookr -f migrations/002_seed_locations.sql

The seed file (002_seed_locations.sql) includes common ports like Tokyo, Hamburg, Shanghai, Rotterdam, and major carriers. This ensures the location extraction works correctly for common routes.

Alternative: Manual data entry If you prefer to add locations manually:

-- Example carriers
INSERT INTO carriers (name, carrier_code, mode) VALUES
  ('Maersk', 'MAEU', 'ocean'),
  ('Hapag-Lloyd', 'HLAG', 'ocean'),
  ('MSC', 'MSC', 'ocean');

-- Example locations (with UNLOCODES for SeaRates integration)
INSERT INTO locations (name, unlocode, location_type, country_code) VALUES
  ('Shanghai', 'CNSHA', 'port', 'CN'),
  ('Rotterdam', 'NLRTM', 'port', 'NL'),
  ('Los Angeles', 'USLAX', 'port', 'US'),
  ('Hamburg', 'DEHAM', 'port', 'DE'),
  ('Tokyo', 'JPTYO', 'port', 'JP');

Development

Start Development Server

# Start with hot-reloading (recommended)
elizaos dev

# OR start production build
elizaos start

The application will be available at http://localhost:3000 by default.

Build

# Build for production
bun run build

# Build with watch mode
bun run build:watch

Usage

Bookr is a chat-based agent system. All interactions happen through natural language conversations in the web interface.

Accessing the Chat Interface

  1. Start the development server: elizaos dev
  2. Open http://localhost:3000 in your browser
  3. Navigate to the chat/agent interface (look for "Chat" or "Agent" in navigation)

Booking Commands

Note: Bookr currently only handles ocean container shipments (FCL/LCL) between China and the European Union. Requests outside this scope will be politely declined.

Get Quotes

Request shipping quotes using natural language for China-EU routes:

Get quotes from Shanghai to Rotterdam
Fetch rates for shipping from Shanghai to Los Angeles
Find quotes from Hamburg to New York

What happens:

  • Agent checks database for existing quotes
  • If no quotes or quotes are stale (>24 hours), fetches from SeaRates API (if configured)
  • Scores and ranks quotes based on user preferences
  • Returns top quotes with detailed information

Rank & Compare Rates

Rank rates from Shanghai to Rotterdam
Compare the best shipping rates
Show me the top quotes for this route

Configure Preferences

Set your ranking preferences using natural language:

Prioritize cost over speed
Set price to high, time to medium, co2 to low
I care more about price than time

Weight Levels:

  • low: ~10% weight
  • medium: ~50% weight
  • high: ~90% weight

Weights are automatically normalized to sum to 100%.

Default Preferences:

  • Price: 55%
  • Time: 35%
  • CO₂: 10%

APM Terminals Commands

Query vessel schedules:

What vessels are scheduled at Los Angeles terminal?
Check vessel ETA at Rotterdam terminal
Show me vessel schedules for Barcelona

Example Conversation Flow

User: Get quotes from Shanghai to Rotterdam

Agent: I found 3 quotes for Shanghai → Rotterdam:
      1. Maersk - $2,500 USD - 28 days - Score: 0.85
      2. Hapag-Lloyd - $2,650 USD - 26 days - Score: 0.82
      3. MSC - $2,400 USD - 30 days - Score: 0.78

User: Prioritize speed over cost

Agent: Preferences updated:
      - Price: medium (35%)
      - Time: high (55%)
      - CO₂: low (10%)

User: Rank those quotes again

Agent: Here are the re-ranked quotes (prioritizing speed):
      1. Hapag-Lloyd - $2,650 USD - 26 days - Score: 0.91
      2. Maersk - $2,500 USD - 28 days - Score: 0.88
      3. MSC - $2,400 USD - 30 days - Score: 0.75

Scope Limitations

Important: Bookr currently has a focused scope:

  • Supported: Ocean container shipments (FCL/LCL) between China and the European Union
  • Not Supported:
    • Air freight, road, rail, or bulk shipments
    • Routes outside China-EU
    • Parcel shipments
    • Project cargo

If you request services outside this scope, Bookr will politely decline and explain the current limitations.

UI Testing Guide

Manual Testing Workflow

  1. Start the application:

    elizaos dev
  2. Open the chat interface at http://localhost:3000

  3. Test basic chat:

    • Send a greeting message
    • Verify agent responds
  4. Test booking features:

    • Request quotes: "Get quotes from Shanghai to Rotterdam"
    • Configure preferences: "Prioritize cost over speed"
    • Request quotes again (should reflect new preferences)
    • Test different routes
  5. Test SeaRates integration (if API key configured):

    • Request quotes for a route with no database entries
    • Verify API call in logs: "Fetched quotes from SeaRates API"
    • Check quotes are stored in database
  6. Test APM Terminals (if configured):

    • Query vessel schedules: "What vessels are at Los Angeles?"

Automated Testing

Run All Tests

# Run all tests (component + e2e)
bun run test

# Run component tests only
bun run test:component

# Run e2e tests only
bun run test:e2e

Cypress UI Tests

# Open Cypress Test Runner (interactive)
bun run cypress:open

# Run E2E tests headless
bun run cypress:e2e

# Run component tests
bun run cypress:component

Available Test Suites:

  • agent-chat.cy.ts - Chat interface functionality
  • user-workflow.cy.ts - Complete user journeys
  • dashboard.cy.ts - Dashboard and navigation

Testing Checklist

✅ Chat interface loads and displays correctly
✅ Messages can be sent (Enter key and Send button)
✅ Agent responds to queries
✅ Booking commands are recognized
✅ Quotes are returned and displayed
✅ Preferences can be updated
✅ Preferences persist across sessions
✅ SeaRates API integration works (if configured)
✅ Error handling for invalid locations
✅ Database persistence verified

Project Structure

bookr/
├── src/
│   ├── character.ts          # Character/agent configuration
│   ├── plugins/
│   │   ├── booking/          # Booking plugin (quotes, ranking, preferences)
│   │   │   ├── index.ts
│   │   │   ├── service.ts
│   │   │   ├── quoting-engine.ts
│   │   │   ├── scoring.ts
│   │   │   ├── user-preferences.ts
│   │   │   └── types.ts
│   │   ├── searates/         # SeaRates API integration
│   │   │   ├── index.ts
│   │   │   ├── service.ts
│   │   │   └── types.ts
│   │   └── apm-terminals/     # APM Terminals vessel schedules
│   │       ├── index.ts
│   │       ├── service.ts
│   │       └── scoring.ts
│   ├── frontend/              # React frontend
│   │   ├── index.tsx
│   │   └── index.css
│   └── __tests__/            # Test suites
│       ├── cypress/
│       │   ├── component/    # Component tests
│       │   └── e2e/          # E2E tests
│       └── e2e/              # Runtime E2E tests
├── migrations/                # Database migrations
│   └── 001_initial_schema.sql
├── SEARATES_INTEGRATION.md    # SeaRates setup guide
└── README.md                  # This file

Scoring Algorithm

Quotes are ranked using a transparent, deterministic algorithm:

priceNorm = min(1, medianPrice / quote.price)      // cheaper → closer to 1
timeNorm  = min(1, minTransit / quote.transitDays) // faster → closer to 1
co2Norm   = min(1, medianCO2 / quote.co2kg)        // greener → closer to 1
validityPenalty = quote.validityUntil < (today + 3d) ? 0.8 : 1.0

score = validityPenalty * (wPrice*priceNorm + wTime*timeNorm + wCO2*co2Norm)

Scoring Factors:

  • Price: Normalized against median price (cheaper = better)
  • Time: Normalized against minimum transit time (faster = better)
  • CO₂: Normalized against median emissions (lower = better)
  • Validity: Penalty (0.8x) for quotes expiring within 3 days

Plugins

Booking Plugin

Provides core booking functionality:

  • Quote fetching and storage
  • Rate ranking with scoring algorithm
  • User preference management
  • Natural language action recognition

See src/plugins/booking/README.md for detailed documentation.

SeaRates Plugin

Integrates with DPWorld SeaRates Logistics Explorer API:

  • Real-time quote fetching for FCL, LCL, Air, Road, Rail, Bulk
  • Automatic quote refresh for stale data
  • Rate limit tracking (20 calls per transport mode)
  • Carrier auto-discovery

See src/plugins/searates/README.md and SEARATES_INTEGRATION.md for setup details.

APM Terminals Plugin

Provides vessel schedule queries:

  • Query schedules by terminal code or city name
  • Intelligent schedule ranking
  • OAuth 2.0 authentication
  • Support for all APM terminals worldwide

See src/plugins/apm-terminals/README.md for details.

API Limitations

SeaRates API

  • 20 shipments per transport type (FCL, LCL, Air, Road, Rail, Bulk)
  • 20 API calls per transport type (rate limit)
  • Valid until: October 24, 2025

The system automatically tracks usage and prevents exceeding limits.

Troubleshooting

No quotes returned

  • Check API credentials in .env
  • Verify locations have UNLOCODES in database
  • Check API logs for errors
  • Verify API key is valid and not expired

Rate limit errors

  • Check callCounts in service logs
  • Each transport mode has 20 call limit
  • System logs warnings when approaching limits

Database connection errors

  • Verify DATABASE_URL in .env
  • Ensure PostgreSQL is running
  • Check database exists: psql -l | grep bookr
  • Verify migration has been run

Agent not responding

  • Check LLM provider API key is set
  • Verify at least one LLM provider is configured
  • Check server logs for errors
  • Verify agent is running: elizaos dev

Testing

Test Structure

ElizaOS employs a dual testing strategy:

  1. Component Tests (src/__tests__/*.test.ts)

    • Fast, isolated tests using mocks
    • Run with Bun's native test runner
  2. E2E Tests (src/__tests__/e2e/*.e2e.ts & cypress/e2e/)

    • Real runtime with actual database
    • Test complete user scenarios
    • Cypress for UI testing

Running Tests

# All tests
bun run test

# Component tests only
bun run test:component

# E2E tests only  
bun run test:e2e

# Cypress UI tests
bun run cypress:open      # Interactive
bun run cypress:e2e       # Headless E2E
bun run cypress:component # Component tests

Character Configuration

Bookr is configured as a no-nonsense logistics orchestrator with the following characteristics:

  • Scope: Ocean container shipments (FCL/LCL) between China and the European Union
  • Personality: Pragmatic, decisive, and solution-oriented
  • Communication Style: Direct, operational language with structured checklists and timelines
  • Focus Areas: Safety, compliance, trade-offs (speed, cost, risk, sustainability)

Customize your project by modifying:

  • src/character.ts - Character definition, system prompt, and plugins
  • src/index.ts - Main entry point
  • .env - Environment variables
  • migrations/ - Database schema

License

Part of the Bookr project.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published