Skip to main content

Overview

The Factorio integration enables AIRI to interact with Factorio servers through the RCON (Remote Console) protocol. This allows for game automation, monitoring, and AI-driven factory management.
The Factorio integration is maintained as a separate project: airi-factorio. Documentation here covers the integration architecture and setup overview.

Features

  • RCON API Integration: Execute Lua commands remotely
  • Game State Monitoring: Track resources, production, and entities
  • Factory Automation: AI-driven base building and optimization
  • Vision Model Integration: Computer vision for factory analysis
  • Event-Driven Architecture: React to game events in real-time
  • Plugin System: Extend with custom automation scripts

Architecture

The Factorio integration uses a modular architecture:

Prerequisites

  • Factorio server (headless or GUI)
  • RCON enabled on Factorio server
  • Python 3.8+ (for vision pipeline)
  • Node.js 18+ (for AIRI integration)
  • AIRI server runtime

Setup

1. Enable RCON on Factorio Server

Edit your Factorio server settings (server-settings.json):
{
  "name": "AIRI Factorio Server",
  "description": "Server with AIRI automation",
  "_comment_rcon": "RCON configuration",
  "rcon_port": 27015,
  "rcon_password": "your-secure-password"
}
Restart the Factorio server.

2. Configure AIRI Module

In your AIRI configuration (Stage UI or config file):
// Gaming Factorio Module Configuration
{
  enabled: true,
  rconHost: 'localhost',
  rconPort: 27015,
  rconPassword: 'your-secure-password',
  enableVision: true
}
From packages/stage-ui/src/stores/modules/gaming-factorio.ts:1:
import { createGamingModuleStore } from './gaming-module-factory'

export const useFactorioStore = createGamingModuleStore('factorio', 34197)

3. Clone airi-factorio Project

git clone https://github.com/moeru-ai/airi-factorio.git
cd airi-factorio

4. Install Dependencies

# Node.js dependencies
pnpm install

# Python dependencies (for vision)
pip install -r requirements.txt

5. Configure Environment

cp .env.example .env
Edit .env:
# Factorio RCON
FACTORIO_HOST=localhost
FACTORIO_RCON_PORT=27015
FACTORIO_RCON_PASSWORD=your-secure-password

# AIRI Connection
AIRI_WS_URL=ws://localhost:6121/ws
AIRI_TOKEN=your-airi-token

# Vision Model
VISION_MODEL=yolov8
VISION_CONFIDENCE=0.5

# LLM for reasoning
OPENAI_API_KEY=sk-...
OPENAI_MODEL=gpt-4o

6. Start the Integration

pnpm start

Usage

Basic Commands

Send commands to AIRI through any connected interface (Discord, Telegram, etc.):
Check my Factorio factory status
Build a new iron smelting array
Optimize my copper production
Show me the pollution levels
Research military science

RCON API

Execute raw Lua commands:
import { FactorioClient } from 'airi-factorio'

const client = new FactorioClient({
  host: 'localhost',
  port: 27015,
  password: 'your-secure-password'
})

// Execute command
await client.send('/c game.print("Hello from AIRI!")')

// Get game state
const players = await client.send('/players')
const time = await client.send('/time')

Vision Analysis

The vision pipeline can analyze factory screenshots:
from airi_factorio.vision import FactorioVision

vision = FactorioVision(model='yolov8')

# Analyze screenshot
results = vision.analyze('factory_screenshot.png')

print(f"Detected entities: {results.entities}")
print(f"Belt throughput: {results.belt_analysis}")
print(f"Bottlenecks: {results.bottlenecks}")

Automation Examples

Auto-Research

// Auto-research next technology
async function autoResearch() {
  const tech = await selectNextTech()
  await rcon.send(`/c game.forces.player.research_queue_add("${tech}")`)
}

Resource Monitor

// Monitor resource production
async function monitorResources() {
  const data = await rcon.send('/c game.print(serpent.block(game.forces.player.item_production_statistics.input_counts))')
  
  const resources = parseResources(data)
  
  if (resources['iron-plate'] < 1000) {
    await alertLowResources('iron-plate')
  }
}

Factory Builder

// Build production line
async function buildProductionLine(recipe: string, x: number, y: number) {
  const layout = generateLayout(recipe)
  
  for (const entity of layout.entities) {
    await rcon.send(`/c game.surfaces[1].create_entity{
      name="${entity.name}",
      position={${x + entity.x}, ${y + entity.y}},
      force="player"
    }`)
  }
}

Plugin Development

Create custom automation plugins:
// plugins/auto-defense.ts
export default {
  name: 'auto-defense',
  version: '1.0.0',
  
  async onLoad(bot) {
    bot.on('entity-damaged', async (event) => {
      if (event.entity.type === 'player') {
        await bot.rcon.send('/c game.forces.player.set_spawn_position({0, 0}, game.surfaces[1])')
      }
    })
  },
  
  async onUnload(bot) {
    // Cleanup
  }
}
Register plugin:
import autoDefense from './plugins/auto-defense'

await factorioBot.loadPlugin(autoDefense)

Vision Model Training

The integration supports custom YOLO models trained on Factorio:

Dataset Structure

dataset/
├── images/
│   ├── train/
│   └── val/
├── labels/
│   ├── train/
│   └── val/
└── data.yaml

Training

python train.py --data dataset/data.yaml --epochs 100 --img 640

Deployment

cp runs/train/exp/weights/best.pt models/factorio_yolo.pt
Update .env:
VISION_MODEL_PATH=models/factorio_yolo.pt

Configuration Reference

Module Settings

interface FactorioModuleConfig {
  enabled: boolean
  rconHost: string
  rconPort: number
  rconPassword: string
  enableVision: boolean
  visionModel?: string
  autoResearch?: boolean
  autoDefense?: boolean
  pollInterval?: number  // milliseconds
}

RCON Commands

Common Lua commands:
-- Get player position
/c game.player.print(serpent.line(game.player.position))

-- List all entities
/c game.print(serpent.block(game.player.surface.find_entities()))

-- Research tech
/c game.forces.player.research_queue_add("automation")

-- Spawn entity
/c game.surfaces[1].create_entity{name="assembling-machine-1", position={0, 0}}

-- Get production stats
/c game.print(serpent.block(game.forces.player.item_production_statistics.output_counts))

Troubleshooting

RCON connection refused

  1. Verify RCON is enabled in server-settings.json
  2. Check firewall allows port 27015
  3. Confirm password is correct
  4. Restart Factorio server

Vision model not detecting

  1. Ensure model is trained on Factorio data
  2. Check confidence threshold (try lowering)
  3. Verify screenshot quality and resolution
  4. Update to latest model weights

Commands not executing

  1. Check Lua syntax in RCON commands
  2. Verify player permissions
  3. Review Factorio logs for errors
  4. Test commands in Factorio console first

Performance Considerations

  • Polling Interval: Balance between responsiveness and server load (recommended: 1000ms)
  • Vision Analysis: CPU-intensive, consider running on separate machine
  • RCON Limits: Some servers limit command rate
  • Memory: Vision model requires ~2GB GPU RAM

External Resources

Next Steps

Training Custom Models

Train YOLO models on your factory

Plugin Development

Build custom automation plugins

Build docs developers (and LLMs) love