Files
loyal_companion/docs/implementation/conversation-gateway.md
latte dde2649876
All checks were successful
Enterprise AI Code Review / ai-review (pull_request) Successful in 35s
phase 1
2026-01-31 18:44:29 +01:00

472 lines
14 KiB
Markdown

# Conversation Gateway Implementation Guide
## Phase 1: Complete ✅
This document describes the Conversation Gateway implementation completed in Phase 1 of the multi-platform expansion.
---
## What Was Implemented
### 1. Platform Abstraction Models
**File:** `src/loyal_companion/models/platform.py`
Created core types for platform-agnostic conversation handling:
- **`Platform` enum:** DISCORD, WEB, CLI
- **`IntimacyLevel` enum:** LOW, MEDIUM, HIGH
- **`ConversationContext`:** Metadata about the conversation context
- **`ConversationRequest`:** Normalized input format from any platform
- **`ConversationResponse`:** Normalized output format to any platform
- **`MoodInfo`:** Mood metadata in responses
- **`RelationshipInfo`:** Relationship metadata in responses
**Key features:**
- Platform-agnostic data structures
- Explicit intimacy level modeling
- Rich context passing
- Response metadata for platform-specific formatting
---
### 2. Conversation Gateway Service
**File:** `src/loyal_companion/services/conversation_gateway.py`
Extracted core conversation logic into a reusable service:
```python
class ConversationGateway:
async def process_message(
request: ConversationRequest
) -> ConversationResponse
```
**Responsibilities:**
- Accept normalized `ConversationRequest` from any platform
- Load conversation history from database
- Gather Living AI context (mood, relationship, style, opinions)
- Apply intimacy-level-based prompt modifiers
- Invoke AI service
- Save conversation to database
- Update Living AI state asynchronously
- Return normalized `ConversationResponse`
**Key features:**
- Platform-agnostic processing
- Intimacy-aware behavior modulation
- Safety boundaries at all intimacy levels
- Async Living AI updates
- Sentiment estimation
- Fact extraction (respects intimacy level)
- Proactive event detection (respects intimacy level)
---
### 3. Intimacy Level System
**Behavior modulation by intimacy level:**
#### LOW (Discord Guilds)
- Brief, light responses
- No deep emotional topics
- No personal memory surfacing
- Minimal proactive behavior
- Grounding language only
- Public-safe topics
#### MEDIUM (Discord DMs)
- Balanced warmth and depth
- Personal memory references allowed
- Moderate emotional engagement
- Casual but caring tone
- Moderate proactive behavior
#### HIGH (Web, CLI)
- Deeper reflection permitted
- Emotional naming encouraged
- Silence tolerance
- Proactive follow-ups allowed
- Deep memory surfacing
- Thoughtful, considered responses
**Safety boundaries (enforced at ALL levels):**
- Never claim exclusivity
- Never reinforce dependency
- Never discourage external connections
- Always defer crisis situations
- No romantic/sexual framing
---
### 4. Service Integration
**File:** `src/loyal_companion/services/__init__.py`
- Exported `ConversationGateway` for use by adapters
- Maintained backward compatibility with existing services
---
## Architecture
```
┌─────────────────────────────────────────────────────────┐
│ Platform Adapters │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ Discord │ │ Web │ │ CLI │ │
│ │ Adapter │ │ Adapter │ │ Adapter │ │
│ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘ │
└─────────┼─────────────────┼─────────────────┼───────────┘
│ │ │
└────────┬────────┴────────┬────────┘
▼ ▼
┌─────────────────────────────────────┐
│ ConversationRequest │
│ - user_id │
│ - platform │
│ - message │
│ - context (intimacy, metadata) │
└─────────────────────────────────────┘
┌─────────────────────────────────────┐
│ ConversationGateway │
│ │
│ 1. Load conversation history │
│ 2. Gather Living AI context │
│ 3. Apply intimacy modifiers │
│ 4. Build enhanced system prompt │
│ 5. Invoke AI service │
│ 6. Save conversation │
│ 7. Update Living AI state │
└─────────────────────────────────────┘
┌─────────────────────────────────────┐
│ ConversationResponse │
│ - response (text) │
│ - mood (optional) │
│ - relationship (optional) │
│ - extracted_facts (list) │
│ - platform_hints (dict) │
└─────────────────────────────────────┘
┌───────────────┼───────────────┐
▼ ▼ ▼
┌─────────┐ ┌─────────┐ ┌─────────┐
│ Discord │ │ Web │ │ CLI │
│ Format │ │ Format │ │ Format │
└─────────┘ └─────────┘ └─────────┘
```
---
## Usage Example
```python
from loyal_companion.models.platform import (
ConversationContext,
ConversationRequest,
IntimacyLevel,
Platform,
)
from loyal_companion.services import ConversationGateway
# Create gateway
gateway = ConversationGateway()
# Build request (from any platform)
request = ConversationRequest(
user_id="discord:123456789",
platform=Platform.DISCORD,
session_id="channel-987654321",
message="I'm feeling overwhelmed today",
context=ConversationContext(
is_public=False,
intimacy_level=IntimacyLevel.MEDIUM,
guild_id="12345",
channel_id="987654321",
user_display_name="Alice",
),
)
# Process message
response = await gateway.process_message(request)
# Use response
print(response.response) # AI's reply
print(response.mood.label if response.mood else "No mood")
print(response.relationship.level if response.relationship else "No relationship")
```
---
## File Structure
```
loyal_companion/
├── src/loyal_companion/
│ ├── models/
│ │ └── platform.py # ✨ NEW: Platform abstractions
│ ├── services/
│ │ ├── conversation_gateway.py # ✨ NEW: Gateway service
│ │ └── __init__.py # Updated: Export gateway
│ └── cogs/
│ └── ai_chat.py # Unchanged (Phase 2 will refactor)
├── docs/
│ ├── multi-platform-expansion.md # ✨ NEW: Architecture doc
│ ├── architecture.md # Updated: Reference gateway
│ └── implementation/
│ └── conversation-gateway.md # ✨ NEW: This file
├── tests/
│ └── test_conversation_gateway.py # ✨ NEW: Gateway tests
└── verify_gateway.py # ✨ NEW: Verification script
```
---
## What's Next: Phase 2
**Goal:** Refactor Discord adapter to use the Conversation Gateway
**Files to modify:**
- `src/loyal_companion/cogs/ai_chat.py`
**Changes:**
1. Import `ConversationGateway` and platform models
2. Replace `_generate_response_with_db()` with gateway call
3. Build `ConversationRequest` from Discord message
4. Map Discord context to `IntimacyLevel`:
- Guild channels → LOW
- DMs → MEDIUM
5. Format `ConversationResponse` for Discord output
6. Test that Discord functionality is unchanged
**Expected outcome:**
- Discord uses gateway internally
- No user-visible changes
- Gateway is proven to work
- Ready for Web and CLI platforms
---
## Testing Strategy
### Unit Tests (tests/test_conversation_gateway.py)
- Gateway initialization
- Request/response creation
- Enum values
- Intimacy modifiers
- Sentiment estimation
- Database requirement
### Integration Tests (Phase 2)
- Discord adapter using gateway
- History persistence
- Living AI updates
- Multi-turn conversations
### Verification Script (verify_gateway.py)
- Import verification
- Enum verification
- Request creation
- Gateway initialization
- Intimacy modifiers
- Sentiment estimation
---
## Configuration
No new configuration required for Phase 1.
Existing settings still apply:
- `LIVING_AI_ENABLED` - Master switch for Living AI features
- `MOOD_ENABLED` - Mood tracking
- `RELATIONSHIP_ENABLED` - Relationship tracking
- `FACT_EXTRACTION_ENABLED` - Autonomous fact learning
- `PROACTIVE_ENABLED` - Proactive events
- `STYLE_LEARNING_ENABLED` - Communication style adaptation
- `OPINION_FORMATION_ENABLED` - Topic opinion tracking
Phase 3 (Web) will add:
- `WEB_ENABLED`
- `WEB_HOST`
- `WEB_PORT`
- `WEB_AUTH_SECRET`
Phase 4 (CLI) will add:
- `CLI_ENABLED`
- `CLI_DEFAULT_INTIMACY`
- `CLI_ALLOW_EMOJI`
---
## Safety Considerations
### Intimacy-Based Constraints
The gateway enforces safety boundaries based on intimacy level:
**LOW intimacy:**
- No fact extraction (privacy)
- No proactive events (respect boundaries)
- No deep memory surfacing
- Surface-level engagement only
**MEDIUM intimacy:**
- Moderate fact extraction
- Limited proactive events
- Personal memory allowed
- Emotional validation permitted
**HIGH intimacy:**
- Full fact extraction
- Proactive follow-ups allowed
- Deep memory surfacing
- Emotional naming encouraged
**ALL levels enforce:**
- No exclusivity claims
- No dependency reinforcement
- No discouragement of external connections
- Professional boundaries maintained
- Crisis deferral to professionals
---
## Performance Considerations
### Database Requirements
The gateway **requires** a database connection. It will raise `ValueError` if `DATABASE_URL` is not configured.
This is intentional:
- Living AI state requires persistence
- Cross-platform identity requires linking
- Conversation history needs durability
### Async Operations
All gateway operations are async:
- Database queries
- AI invocations
- Living AI updates
Living AI updates happen after the response is returned, so they don't block the user experience.
---
## Known Limitations
### Phase 1 Limitations
1. **Discord-only:** Gateway exists but isn't used yet
2. **No cross-platform identity:** Each platform creates separate users
3. **No platform-specific features:** Discord images/embeds not supported in gateway yet
### To Be Addressed
**Phase 2:**
- Integrate with Discord adapter
- Add Discord-specific features to gateway (images, mentioned users)
**Phase 3:**
- Add Web platform
- Implement cross-platform user identity linking
**Phase 4:**
- Add CLI client
- Add CLI-specific formatting (no emojis, minimal output)
---
## Migration Path
### Current State (Phase 1 Complete)
```python
# Discord Cog (current)
async def _generate_response_with_db(message, user_message):
# All logic inline
# Discord-specific
# Not reusable
```
### Phase 2 (Discord Refactor)
```python
# Discord Cog (refactored)
async def _generate_response_with_db(message, user_message):
request = ConversationRequest(...) # Build from Discord
response = await gateway.process_message(request)
return response.response # Format for Discord
```
### Phase 3 (Web Platform Added)
```python
# Web API
@app.post("/chat")
async def chat(session_id: str, message: str):
request = ConversationRequest(...) # Build from Web
response = await gateway.process_message(request)
return response # Return as JSON
```
### Phase 4 (CLI Platform Added)
```python
# CLI Client
async def talk(message: str):
request = ConversationRequest(...) # Build from CLI
response = await http_client.post("/chat", request)
print(response.response) # Format for terminal
```
---
## Success Criteria
Phase 1 is considered complete when:
- ✅ Platform models created and documented
- ✅ ConversationGateway service implemented
- ✅ Intimacy level system implemented
- ✅ Safety boundaries enforced at all levels
- ✅ Services exported and importable
- ✅ Documentation updated
- ✅ Syntax validation passes
Phase 2 success criteria:
- Discord cog refactored to use gateway
- No regression in Discord functionality
- All existing tests pass
- Living AI updates still work
---
## Conclusion
Phase 1 successfully established the foundation for multi-platform support:
1. **Platform abstraction** - Clean separation of concerns
2. **Intimacy system** - Behavior modulation for different contexts
3. **Safety boundaries** - Consistent across all platforms
4. **Reusable gateway** - Ready for Discord, Web, and CLI
The architecture is now ready for Phase 2 (Discord refactor) and Phase 3 (Web platform).
Same bartender. Different stools. No one is trapped.
---
**Last updated:** 2026-01-31
**Status:** Phase 1 Complete ✅
**Next:** Phase 2 - Discord Refactor