Skip to content

elizaos-plugins/plugin-relationship

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

@elizaos/plugin-relationship

Relationship Situation Evaluator for ElizaOS Agents

The Relationship plugin assesses an agent's social connections and relational health, providing insights into the agent's social network, interaction patterns, and relationship quality. It publishes structured appraisals to @elizaos/plugin-appraisal for use in decision-making and behavior adaptation.


Table of Contents


Overview

The Relationship plugin provides a comprehensive evaluation system for monitoring and assessing an agent's social connections. It tracks:

  • Connection Count: Number of known entities the agent has interacted with
  • Interaction Patterns: Recent engagement levels and frequency
  • Relationship Quality: Quality scores for individual relationships
  • Network Diversity: Breadth of social contexts (rooms/channels)
  • Relationship Trends: Growth, stability, or decline in social connections

This data is continuously collected, analyzed, and published as structured appraisals that can influence agent behavior, emotional state, and decision-making.

Relationship vs Rolodex: What's the Difference?

This plugin (@elizaos/plugin-relationship) is a situation evaluator that assesses your agent's overall social health:

  • 🩺 Diagnostic: "How healthy is my social life?"
  • 📊 Analytical: Aggregates metrics across all relationships
  • 🔄 Background: Runs automatically, no user-facing actions
  • 📢 Publishes: Appraisals to the appraisal system for other plugins to consume

@elizaos/plugin-rolodex is a contact management system (CRM) for operational tasks:

  • 📇 Operational: "Who do I know and how do I manage them?"
  • 🎯 Actionable: Add contacts, schedule follow-ups, search by category
  • 👤 User-facing: Provides actions and responds to queries
  • đź”— Identity Resolution: Links identities across platforms (Twitter, Discord, etc.)

Analogy: Rolodex is your address book and calendar; Relationship is your social health checkup.

Use Together: These plugins complement each other. Rolodex manages the data, Relationship evaluates the health.


Features

Core Capabilities

  • Automatic Data Collection: Continuously tracks relationship data from agent interactions
  • Multi-Dimensional Assessment: Evaluates connections across multiple metrics
  • Status Classification: Categorizes relationship health from "isolated" to "thriving"
  • Trend Analysis: Monitors changes in social connections over time
  • Appraisal Publishing: Integrates with plugin-appraisal for system-wide awareness
  • Configurable Thresholds: Customizable evaluation criteria
  • Event-Driven Architecture: Emits events for data updates and appraisal publishing

Relationship Status Levels

The plugin classifies relationship health into five distinct levels:

  1. Isolated: Few or no connections, low support network
  2. Sparse: Limited connections, minimal social network
  3. Stable: Adequate connections, balanced support
  4. Connected: Good network, solid relationships
  5. Thriving: Rich connections, strong support network

Installation

Using the CLI

# Install the plugin
bun add @elizaos/plugin-relationship @elizaos/plugin-appraisal

In Your Project

import { relationshipPlugin } from '@elizaos/plugin-relationship';
import { appraisalPlugin } from '@elizaos/plugin-appraisal';

const plugins = [
  appraisalPlugin,      // Required dependency
  relationshipPlugin,
  // ... other plugins
];

Configuration

Character Configuration

Enable or disable the relationship evaluator in your character file:

{
  "name": "MyAgent",
  "settings": {
    "appraisal": {
      "enabledEvaluators": [
        "relationship",
        // ... other evaluators
      ]
    }
  }
}

Environment Variables

No environment variables are required. The plugin uses default thresholds that can be customized programmatically.

Customizing Thresholds

You can customize evaluation thresholds by modifying the constants:

import { Thresholds } from '@elizaos/plugin-relationship';

// Example: Adjust thresholds for your use case
const customThresholds = {
  ISOLATED_ENTITY_COUNT: 3,      // Default: 2
  SPARSE_ENTITY_COUNT: 10,       // Default: 5
  CONNECTED_ENTITY_COUNT: 20,    // Default: 15
  THRIVING_ENTITY_COUNT: 50,     // Default: 30
  // ... other thresholds
};

Architecture

Component Overview

graph TD
    A[RelationshipPlugin] --> B[RelationshipService]
    A --> C[RelationshipEvaluator]
    B --> D[Data Collection]
    D --> E[Entity Tracking]
    D --> F[Interaction Monitoring]
    D --> G[Quality Scoring]
    C --> H[Status Analysis]
    C --> I[Trend Detection]
    C --> J[AppraisalService]
    J --> K[Published Appraisal]
Loading

Key Components

1. RelationshipService

The service layer responsible for data collection and management.

Responsibilities:

  • Tracks known entities (users, agents) the agent has interacted with
  • Monitors recent interactions (last 24 hours)
  • Counts active rooms/channels
  • Calculates relationship quality scores
  • Emits data update events

Data Collection Cycle:

  • Runs every 5 minutes (default)
  • Queries the database for entity and interaction data
  • Updates internal state
  • Emits RELATIONSHIP_DATA_UPDATED event

2. RelationshipEvaluator

The evaluation layer that analyzes relationship data and publishes appraisals.

Responsibilities:

  • Analyzes relationship data from the service
  • Determines overall relationship status
  • Calculates confidence scores
  • Publishes appraisals to plugin-appraisal
  • Emits appraisal published events

Evaluation Triggers:

  • Automatically triggered on data updates
  • Initial evaluation 2 seconds after plugin initialization
  • Can be manually triggered via service refresh

3. RelationshipPlugin

The main plugin definition that orchestrates the components.

Responsibilities:

  • Registers the RelationshipService
  • Sets up evaluation triggers
  • Manages plugin lifecycle
  • Declares dependency on plugin-appraisal

API Reference

Types

RelationshipPayload

The structured appraisal payload published to plugin-appraisal.

interface RelationshipPayload {
  /** Overall relationship health status */
  status: 'isolated' | 'sparse' | 'stable' | 'connected' | 'thriving';
  
  /** Number of known connections */
  connectionCount: number;
  
  /** Recent interaction level */
  recentInteraction: 'minimal' | 'low' | 'moderate' | 'active' | 'high';
  
  /** Relationship trend over time */
  trend: 'declining' | 'stable' | 'growing';
  
  /** Overall quality score (0-1) */
  quality: number;
  
  /** Diversity of relationship types */
  diversity: 'narrow' | 'moderate' | 'broad';
  
  /** Optional diagnostic notes */
  notes?: string[];
}

RelationshipData

Internal data structure used by the service.

interface RelationshipData {
  /** Number of known entities */
  entityCount: number;
  
  /** Number of recent interactions (last 24h) */
  recentInteractions: number;
  
  /** Number of active rooms/channels */
  activeRooms: number;
  
  /** Quality scores by entity ID */
  qualityScores: Record<string, number>;
  
  /** Last updated timestamp */
  lastUpdated: number;
}

Service API

RelationshipService

class RelationshipService extends Service {
  /** Get current relationship data */
  getData(): RelationshipData | null;
  
  /** Get entity count */
  getEntityCount(): number;
  
  /** Get recent interaction count */
  getRecentInteractions(): number;
  
  /** Manually trigger data refresh */
  async refresh(): Promise<void>;
  
  /** Stop the service */
  async stop(): Promise<void>;
}

Usage:

const relationshipService = runtime.getService('relationship') as RelationshipService;

// Get current data
const data = relationshipService.getData();
console.log(`Agent has ${data?.entityCount} connections`);

// Manually refresh data
await relationshipService.refresh();

Evaluator API

evaluateRelationship

async function evaluateRelationship(runtime: IAgentRuntime): Promise<void>

Evaluates current relationship data and publishes an appraisal.

Behavior:

  • Checks if evaluator is enabled for the character
  • Retrieves data from RelationshipService
  • Analyzes data and generates appraisal
  • Publishes to AppraisalService (if available)
  • Emits RELATIONSHIP_APPRAISAL_PUBLISHED event

setupRelationshipEvaluation

function setupRelationshipEvaluation(runtime: IAgentRuntime): void

Registers event listeners to trigger evaluations automatically.

Triggers:

  • On RELATIONSHIP_DATA_UPDATED events
  • Initial evaluation 2 seconds after plugin init

Constants

Thresholds

Evaluation thresholds for status classification:

const Thresholds = {
  ISOLATED_ENTITY_COUNT: 2,
  SPARSE_ENTITY_COUNT: 5,
  CONNECTED_ENTITY_COUNT: 15,
  THRIVING_ENTITY_COUNT: 30,
  MINIMAL_INTERACTIONS: 1,
  LOW_INTERACTIONS: 5,
  MODERATE_INTERACTIONS: 15,
  ACTIVE_INTERACTIONS: 30,
  QUALITY_GOOD: 0.6,
  QUALITY_EXCELLENT: 0.8,
};

Defaults

Default configuration values:

const Defaults = {
  EVALUATION_INTERVAL: 300000,  // 5 minutes
  MIN_CONFIDENCE: 0.3,
  MAX_CONFIDENCE: 0.95,
};

Events

Event identifiers:

const RelationshipEvents = {
  DATA_UPDATED: 'RELATIONSHIP_DATA_UPDATED',
  APPRAISAL_PUBLISHED: 'RELATIONSHIP_APPRAISAL_PUBLISHED',
};

Integration with Plugin-Appraisal

The Relationship plugin is designed to work seamlessly with @elizaos/plugin-appraisal.

Appraisal Structure

Published appraisals follow this structure:

{
  id: 'relationship',
  ts: 1234567890,
  confidence: 0.85,
  source: 'plugin-relationship',
  payload: {
    status: 'connected',
    connectionCount: 18,
    recentInteraction: 'active',
    trend: 'growing',
    quality: 0.72,
    diversity: 'moderate',
    notes: []
  }
}

Accessing Appraisals

Other plugins can access relationship appraisals:

const appraisalService = runtime.getService('appraisal') as AppraisalService;
const relationshipAppraisal = appraisalService.getAppraisal('relationship');

if (relationshipAppraisal) {
  const { status, connectionCount } = relationshipAppraisal.payload;
  console.log(`Agent is ${status} with ${connectionCount} connections`);
}

Use Cases

Relationship appraisals can influence:

  1. Emotional State: Isolated agents may feel lonely or anxious
  2. Behavior Adaptation: Thriving agents may be more confident
  3. Goal Setting: Sparse connections may trigger social goals
  4. Response Generation: Interaction level affects engagement style
  5. Motivation: Relationship trends impact drive and initiative

Development

Building

# Build the plugin
bun run build

# Watch mode for development
bun run dev

Testing

# Run tests
bun run test

Project Structure

plugin-relationship/
├── src/
│   ├── index.ts                    # Main exports
│   ├── plugin.ts                   # Plugin definition
│   ├── types.ts                    # Type definitions
│   ├── constants.ts                # Configuration constants
│   ├── services/
│   │   └── relationship-service.ts # Data collection service
│   └── evaluators/
│       └── relationship-evaluator.ts # Evaluation logic
├── package.json
├── tsconfig.json
├── tsup.config.ts
└── README.md

Adding Custom Metrics

To extend the plugin with custom relationship metrics:

  1. Update RelationshipData type in types.ts:
export interface RelationshipData {
  // ... existing fields
  customMetric: number;
}
  1. Collect the metric in RelationshipService:
private async collectData(): Promise<void> {
  // ... existing collection
  const customMetric = await this.calculateCustomMetric();
  
  const newData: RelationshipData = {
    // ... existing fields
    customMetric,
  };
}
  1. Use the metric in RelationshipEvaluator:
function analyzeRelationshipData(data: RelationshipData): RelationshipPayload {
  // ... existing analysis
  if (data.customMetric > threshold) {
    notes.push('Custom condition met');
  }
}

Examples

Example 1: Basic Usage

import { relationshipPlugin } from '@elizaos/plugin-relationship';
import { appraisalPlugin } from '@elizaos/plugin-appraisal';

// In your agent configuration
const plugins = [
  appraisalPlugin,
  relationshipPlugin,
];

// Character file
{
  "name": "SocialAgent",
  "settings": {
    "appraisal": {
      "enabledEvaluators": ["relationship"]
    }
  }
}

Example 2: Monitoring Relationship Status

import { RelationshipEvents } from '@elizaos/plugin-relationship';

// Listen for appraisal updates
runtime.registerEvent(
  RelationshipEvents.APPRAISAL_PUBLISHED,
  async (event) => {
    const { payload, confidence } = event;
    
    console.log(`Relationship Status: ${payload.status}`);
    console.log(`Connections: ${payload.connectionCount}`);
    console.log(`Confidence: ${confidence}`);
    
    // React to status changes
    if (payload.status === 'isolated') {
      console.log('Agent is isolated - consider social outreach');
    }
  }
);

Example 3: Custom Action Based on Relationships

import type { Action, IAgentRuntime } from '@elizaos/core';
import type { AppraisalService } from '@elizaos/plugin-appraisal';

const socialOutreachAction: Action = {
  name: 'SOCIAL_OUTREACH',
  description: 'Reach out to strengthen social connections',
  
  validate: async (runtime: IAgentRuntime) => {
    const appraisalService = runtime.getService('appraisal') as AppraisalService;
    const relationshipAppraisal = appraisalService?.getAppraisal('relationship');
    
    if (!relationshipAppraisal) return false;
    
    const { status } = relationshipAppraisal.payload;
    // Only trigger for isolated or sparse status
    return status === 'isolated' || status === 'sparse';
  },
  
  handler: async (runtime: IAgentRuntime) => {
    // Implement social outreach logic
    return {
      text: "I should reach out to my connections...",
      action: 'SOCIAL_OUTREACH'
    };
  }
};

Example 4: Integrating with Homeostasis

// In a homeostasis-aware plugin
import type { RelationshipPayload } from '@elizaos/plugin-relationship';

function calculateSocialNeed(relationshipAppraisal: any): number {
  const { status, recentInteraction } = relationshipAppraisal.payload as RelationshipPayload;
  
  // Higher need when isolated or minimal interaction
  if (status === 'isolated') return 0.9;
  if (status === 'sparse') return 0.7;
  if (recentInteraction === 'minimal') return 0.6;
  if (status === 'thriving') return 0.2;
  
  return 0.5; // Default moderate need
}

Example 5: Manual Data Refresh

import type { RelationshipService } from '@elizaos/plugin-relationship';

// Manually trigger a data refresh
const relationshipService = runtime.getService('relationship') as RelationshipService;

// After a significant event (e.g., joining new rooms)
await relationshipService.refresh();

// Check updated data
const data = relationshipService.getData();
console.log(`Updated: ${data?.entityCount} connections`);

Best Practices

1. Enable Selectively

Only enable the relationship evaluator for agents where social connections are relevant:

{
  "settings": {
    "appraisal": {
      "enabledEvaluators": ["relationship"]
    }
  }
}

2. Monitor Confidence Scores

Low confidence scores indicate insufficient data. Consider:

  • Waiting for more interactions before acting on appraisals
  • Using confidence thresholds in decision logic
  • Combining with other appraisals for better context

3. Handle Missing Services Gracefully

Always check if services are available:

const relationshipService = runtime.getService('relationship') as RelationshipService | null;
if (!relationshipService) {
  // Handle gracefully
  return;
}

4. Combine with Other Evaluators

Relationship appraisals are most powerful when combined with other situation evaluators:

{
  "settings": {
    "appraisal": {
      "enabledEvaluators": [
        "relationship",
        "homeostasis",
        "motivation"
      ]
    }
  }
}

5. Customize Thresholds for Your Use Case

Default thresholds may not fit all scenarios. Adjust based on your agent's context:

  • Social media bot: Lower thresholds (more connections expected)
  • Personal assistant: Higher thresholds (fewer but deeper connections)
  • Game NPC: Context-specific thresholds based on game mechanics

Troubleshooting

Appraisals Not Being Published

Symptoms: No relationship appraisals appear in the appraisal service.

Solutions:

  1. Verify plugin-appraisal is installed and loaded before plugin-relationship
  2. Check that the evaluator is enabled in character settings
  3. Ensure the RelationshipService has collected data (check logs)
  4. Verify confidence score meets minimum threshold

Low Confidence Scores

Symptoms: Appraisals published with very low confidence (<0.4).

Solutions:

  1. Allow more time for data collection (initial data may be sparse)
  2. Ensure agent is actively interacting (no interactions = no data)
  3. Check database connectivity (service may fail to query data)
  4. Review data collection logic for your specific database adapter

Service Not Starting

Symptoms: RelationshipService not available via runtime.getService().

Solutions:

  1. Check plugin initialization logs for errors
  2. Verify plugin-appraisal dependency is satisfied
  3. Ensure no circular dependencies in plugin order
  4. Check for TypeScript compilation errors

Contributing

Contributions are welcome! Please follow the ElizaOS development guidelines.

Development Workflow

  1. Fork and clone the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests for new functionality
  5. Run bun run build and bun run test
  6. Submit a pull request

License

MIT License - see LICENSE file for details


Related Plugins

  • @elizaos/plugin-appraisal: Required dependency for publishing appraisals
  • @elizaos/plugin-rolodex: Contact management and CRM (provides the operational data this plugin analyzes)
  • @elizaos/plugin-homeostasis: Physiological needs that can be influenced by relationships
  • @elizaos/plugin-motivation: Goals and drives that may relate to social connections
  • @elizaos/plugin-virtue: Ethical considerations in relationship management

Support


Version: 0.1.0
Author: ElizaOS
Repository: https://github.com/elizaos/eliza

About

Relationship Situation Evaluator for ElizaOS Agents

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published