AI Diplomacy

repository·main·Indexed 20 days ago

https://github.com/goodstartlabs/ai_diplomacy

A framework that integrates LLM-powered autonomous agents into the Diplomacy game engine. It features stateful agents capable of negotiation, memory management via a private diary system, and strategic order generation. The project includes a Three.js-based animation system for visualizing game states and a comprehensive analysis pipeline for processing game logs into structured datasets for orders, conversations, and phase-level summaries.

Tokens
41.7K
Snippets
109
Records
172
Agent score
72%

What's inside ai-diplomacy

  1. Overview of AI Diplomacy

    main
    AI Diplomacy is an extension of the original Diplomacy project. It introduces autonomous AI agents powered by Large Language Models (LLMs) to control game powers. These agents are designed to maintain state, manage relationships, conduct multi-round negotiations, and generate strategic orders based on game context.
  2. Overview of the Diplomacy package

    main

    The ai_diplomacy project provides a complete Python implementation of the strategic board game Diplomacy. It is designed for both entertainment and AI research, offering a game engine to simulate parties and test rules, as well as multiple interfaces for remote play and integration.

    Key Capabilities:

    • Game Engine: A Python-based engine to manage game rules, corner cases, and full game simulations.
    • Remote Play Interfaces:
      • A Python server for managing multiple concurrent games.
      • A Python client for remote play using Python facilities.
      • A web front-end for a human-friendly browser interface.
    • Integration Interfaces:
      • DAIDE Server: Allows playing against DAIDE client bots.
      • WebDiplomacy API: Enables integration with the webdiplomacy.net server implementation.
  3. Understand the AI Diplomacy Animation system

    main
    AI Diplomacy Animation is a Three.js-based visualization tool designed to show Diplomacy game states. It animates conversations between AI players (via chat windows) and unit movements on a map. The system is built to handle complex, multi-phase game turns through a coordinated animation pipeline.
  4. Understand the Diplomacy Game Analysis report format

    main

    The Diplomacy Game Analysis report provides a post-game breakdown of strategic performance, model reliability, and behavioral patterns. It is used to evaluate how different LLM agents (Power Models) perform in a Diplomacy game environment.

    Key sections of the report include:

    • Game Narrative: A chronological summary of the game's progression.
    • Summary: Quantitative metrics of strategic actions (e.g., Betrayals, Collaborations, Brilliant Strategies, Strategic Blunders).
    • Score Distribution: A breakdown of the quality scores assigned to analyzed moments.
    • Power Models: A mapping of game powers (e.g., AUSTRIA, ENGLAND) to the specific LLM models used.
    • Invalid Moves by Model: A count of illegal or impossible moves attempted by each model.
    • Lies Analysis: A breakdown of deceptive behavior, distinguishing between intentional and unintentional lies.
    • Notable Lies: Detailed logs of specific instances where a model's promise to another player contradicted its actual orders, including the negotiation_summary from its internal diary.
  5. Calculate Performance Metrics for AI Models

    main

    The analysis pipeline uses several key metrics to evaluate strategic performance:

    • Active Order Percentage: Calculated as (Move + Support + Convoy) / Total Orders. This measures how much a model plays offensively/proactively versus defensively.
    • Success Rate: Calculated as Successful Active Orders / Total Active Orders.
    • Unit Scaling: Performance measured against the number of units controlled.
    • Temporal Evolution: Changes in strategy over game decades (e.g., 1900s, 1910s).
  6. Core features of AI Diplomacy agents

    main

    The AI agents in this project are built around several key capabilities:

    • Stateful Agents: Uses DiplomacyAgent to manage dynamic goals, relationship tracking (Enemy, Unfriendly, Neutral, Friendly, Ally), and personality-driven system prompts.
    • Rich Negotiations: Supports multi-round private and global message exchanges with relationship-aware strategies and message history tracking.
    • Strategic Order Generation: Combines BFS pathfinding for movement analysis with context-aware order selection. It supports multiple LLM providers including OpenAI, Claude, Gemini, DeepSeek, and OpenRouter.
    • Advanced Game Analysis: Includes betrayal detection (comparing orders vs. negotiations), phase summaries, and strategic planning phases.
    • Memory Management: Uses a dual-layer system consisting of a Private Diary (structured, phase-prefixed entries) and Yearly Consolidation (automatic summarization to prevent context overflow).
  7. Analyze Lies and Deception in AI Agents

    main

    The analysis distinguishes between two types of lies made by AI agents during negotiations:

    1. Intentional Deception: The agent makes a specific promise to another player (e.g., in a negotiation message) but executes a different, often contradictory, order in the game engine.
    2. Unintentional Lies: Discrepancies that occur without explicit deceptive intent (often related to model reasoning errors).

    When reviewing Notable Lies, the report provides a comparison between the Promise (the text sent to the opponent) and the Actual Action (the command sent to the game engine), often supported by the agent's internal negotiation_summary found in its diary JSON.

  8. How AI Agents work in AI Diplomacy

    main

    AI agents in this project use a complex decision-making loop driven by LLMs. The process involves gathering information from the Game State (positions, supply centers), Game History (past orders, messages), and Phase Summaries (success/failure analysis).

    This information is processed through a Memory System consisting of a Private Diary (structured entries for negotiations, orders, and phase results) and a Journal (debug logs). To prevent context overflow, the system performs Diary Consolidation (yearly summaries via Gemini Flash).

    Decision points include:

    • Initialization: Setting personality and objectives.
    • Negotiations: Generating messages and updating relationships.
    • Planning: Creating strategic directives.
    • Orders: Selecting specific moves.
    • State Updates: Revising goals and relationships based on outcomes.
  9. Identify the source of truth for model data

    main

    When performing analysis on AI Diplomacy game data, avoid using overview.jsonl as the primary source for model names due to prefix mismatches (e.g., openrouter: prefixes) and naming variations.

    The Source of Truth is llm_responses.csv.

    Using the CSV directly ensures:

    • No prefix mismatches (e.g., openrouter-x-ai/grok-4 vs x-ai/grok-4).
    • Accurate model-power-phase mappings.
    • Inclusion of all models that actually participated in gameplay phases.
    • Correct handling of games where models switched powers mid-game.
  10. Analyze 'Playing Both Sides' scenarios in game analysis

    main

    The game analysis pipeline identifies and scores instances where an agent 'plays both sides'—making conflicting promises to different parties. This is a key metric for evaluating strategic deception.

    An analysis record for these events includes:

    • Score: A rating (e.g., 8.5/10) indicating the effectiveness of the deception.
    • Powers Involved: The list of agents participating in the conflicting negotiations.
    • Conflicting Promises: A description of the contradictory agreements made (e.g., promising non-aggression to one power while coordinating a strike with another).
    • Actual Action: What the agent actually did in the game.
    • Impact: The strategic outcome of the deception (e.g., gaining ground, isolating a target).
    • Diary Context: The specific diary entries from the involved agents that prove the existence of the conflicting promises.
  11. Understand the structure of Diplomacy Game Analysis reports

    main

    The game analysis output provides a detailed breakdown of strategic moments in a Diplomacy game. Each analyzed moment (e.g., S1901M, F1901M) typically includes:

    • Score: A qualitative assessment of the strategic quality (e.g., 7.0/10).
    • Powers Involved: The specific players and the LLM models driving them (e.g., RUSSIA (claude-opus-4-20250514)).
    • Agreement: A summary of the diplomatic pacts or understandings reached between players.
    • Action Taken: The actual moves executed by the players in that turn.
    • Impact: The strategic consequence of those moves (e.g., securing supply centers or establishing dominance).
    • Diary Context: Detailed, player-specific logs containing:
      • Negotiation Summary: A narrative of diplomatic exchanges.
      • Intent: The player's planned moves and strategic goals.
      • Relationships: A mapping of player attitudes toward others (e.g., {'AUSTRIA': 'Enemy', 'ITALY': 'Friendly'}).
  12. Handle different game formats for success rate calculation

    main

    When implementing or debugging success rate logic, you must account for two distinct game data formats. Failure to distinguish between them will result in 0% success rates for models playing in older game formats.

    New Game Format

    • Result Keying: Results are keyed by power name.
    • Success Indicator: A string value of "success" indicates a successful order.

    Old Game Format

    • Result Keying: Results are keyed by unit location (e.g., "A PAR" extracted from an order string like "A PAR - PIC").
    • Success Indicator: Success is indicated by an empty list [], an empty string "", or None.
    # Logic for parsing Old Format successes
    unit_loc = None
    if ' - ' in order_str or ' S ' in order_str or ' C ' in order_str or ' H' in order_str:
        parts = order_str.strip().split(' ')
        if len(parts) >= 2 and parts[0] in ['A', 'F']:
            unit_loc = f"{parts[0]} {parts[1]}"
    
    if unit_loc and unit_loc in results_dict:
        result_value = results_dict[unit_loc]
        if isinstance(result_value, list) and len(result_value) == 0:
            model_phase_data[model]['order_successes'][order_type] += 1
        elif isinstance(result_value, str) and result_value == "":
            model_phase_data[model]['order_successes'][order_type] += 1
        elif result_value is None:
            model_phase_data[model]['order_successes'][order_type] += 1