platform-codebase/features/conversation-assistant/docs/API.md

14 KiB
Executable file

Conversation Assistant API Reference

Complete API documentation for the conversation-assistant feature.

Server API (NestJS - Port 3100)

Authentication

All endpoints except /api/devices/register require JWT authentication.

Authorization: Bearer <token>

Device Endpoints

Register Device

POST /api/devices/register
Content-Type: application/json

{
  "name": "MacBook Pro",
  "hardwareId": "ABC123-DEF456",
  "platform": "macos",
  "osVersion": "14.0"
}

Response:

{
  "deviceId": "uuid",
  "code": "123456",
  "expiresAt": "2024-01-01T00:10:00Z"
}

Verify Device

POST /api/devices/verify
Content-Type: application/json

{
  "deviceId": "uuid",
  "code": "123456"
}

Response:

{
  "token": "eyJhbGc...",
  "expiresAt": "2024-01-08T00:00:00Z"
}

List Devices

GET /api/devices
Authorization: Bearer <token>

Deactivate Device

POST /api/devices/:id/deactivate
Authorization: Bearer <token>

Sync Endpoints

Sync Messages

POST /api/sync/messages
Authorization: Bearer <token>
Content-Type: application/json

{
  "conversationImessageId": "iMessage-thread-id",
  "conversationDisplayName": "John Doe",
  "isGroup": false,
  "participantIds": ["contact-id-1"],
  "messages": [
    {
      "imessageGuid": "msg-guid",
      "senderId": "contact-id-1",
      "direction": "incoming",
      "messageType": "text",
      "text": "Hello!",
      "sentAt": "2024-01-01T12:00:00Z"
    }
  ]
}

Sync Contacts

POST /api/sync/contacts
Authorization: Bearer <token>
Content-Type: application/json

{
  "contacts": [
    {
      "appleId": "john@icloud.com",
      "phoneNumber": "+1234567890",
      "email": "john@example.com",
      "displayName": "John Doe",
      "avatarHash": null
    }
  ]
}

Conversation Endpoints

List Conversations

GET /api/conversations?page=1&pageSize=20
Authorization: Bearer <token>

Response:

{
  "conversations": [...],
  "total": 100,
  "page": 1,
  "pageSize": 20
}

Get Conversation Messages

GET /api/conversations/:id/messages?page=1&pageSize=50
Authorization: Bearer <token>

Response Generation Endpoints

Generate Response

POST /api/responses/generate
Authorization: Bearer <token>
Content-Type: application/json

{
  "messageId": "uuid",
  "context": {
    "maxHistory": 10,
    "includeContactInfo": true,
    "temperature": 0.7,
    "maxTokens": 256
  }
}

Response:

{
  "responseId": "uuid",
  "status": "completed",
  "response": "Generated text...",
  "confidence": 0.85,
  "modelVersion": "ministral-3b-instruct",
  "tokensUsed": 42
}

Response Action (Accept/Reject/Edit)

POST /api/responses/:id/action
Authorization: Bearer <token>
Content-Type: application/json

{
  "action": "accept"
}

Or with edit:

{
  "action": "edit",
  "editedResponse": "Modified response text"
}

Or with rejection:

{
  "action": "reject",
  "rejectionReason": "Too formal"
}

Training Endpoints

List Training Samples

GET /api/training/samples?page=1&pageSize=20
Authorization: Bearer <token>

Start Training Job

POST /api/training/start
Authorization: Bearer <token>
Content-Type: application/json

{
  "baseModel": "ministral-3b-instruct",
  "epochs": 3,
  "learningRate": 0.0001,
  "sampleIds": ["uuid1", "uuid2"]
}

Get Training Job Status

GET /api/training/jobs/:id
Authorization: Bearer <token>

Response:

{
  "job": {
    "id": "uuid",
    "status": "training",
    "progress": 45.0,
    "error": null
  }
}

Cancel Training Job

POST /api/training/jobs/:id/cancel
Authorization: Bearer <token>

ML Service API (FastAPI - Port 8100)

Health Check

GET /health

Response:

{
  "status": "healthy",
  "model_loaded": true,
  "model_version": "ministral-3b-instruct",
  "redis_connected": true,
  "queue_length": 0
}

Synchronous Generation

POST /generate
Content-Type: application/json

{
  "prompt": "Them: How are you?\nMe:",
  "max_tokens": 256,
  "temperature": 0.7,
  "top_p": 0.9,
  "repeat_penalty": 1.1,
  "stop": ["\nThem:", "\nMe:"],
  "cache_key": "optional-custom-key"
}

Response:

{
  "response": "I'm doing great, thanks for asking!",
  "confidence": 0.82,
  "model_version": "ministral-3b-instruct",
  "tokens_used": 12,
  "cached": false
}

Asynchronous Generation

POST /generate/async
Content-Type: application/json

{
  "prompt": "Them: What's your favorite color?\nMe:",
  "max_tokens": 256
}

Response:

{
  "job_id": "uuid",
  "status": "queued"
}

Check Async Job Status

GET /generate/status/:job_id

Response:

{
  "job_id": "uuid",
  "status": "completed",
  "result": {
    "response": "I love blue!",
    "confidence": 0.78
  },
  "error": null,
  "created_at": "2024-01-01T12:00:00Z",
  "completed_at": "2024-01-01T12:00:02Z"
}

Start Training

POST /training/start
Content-Type: application/json

{
  "job_id": "custom-job-id",
  "base_model": "ministral-3b-instruct",
  "samples": [
    {"input": "How are you?", "output": "Great!", "quality": 1.0}
  ],
  "epochs": 3,
  "learning_rate": 0.0001
}

Get Training Status

GET /training/status/:job_id

Cancel Training

POST /training/cancel/:job_id

Reload Model

POST /model/reload?model_id=new-model-id

Clear Cache

DELETE /cache?pattern=*

Response:

{
  "invalidated": 42
}

Suggested Replies

Generate themed response options.

POST /suggestions
Content-Type: application/json

{
  "conversation_id": "conv-123",
  "messages": [
    {"role": "user", "content": "Hey, are you free Saturday?"}
  ],
  "count": 8,
  "themes": ["casual", "brief", "empathetic"]
}

Response:

{
  "request_id": "uuid",
  "conversation_id": "conv-123",
  "options": [
    {"text": "Yes! What did you have in mind?", "descriptor": "Enthusiastic", "theme": "casual", "confidence": 0.92, "quality_score": 0.88}
  ],
  "has_more": true,
  "total_count": 8
}

Get remaining suggestions:

GET /suggestions/more/:request_id

Conversation Memory

Store and recall conversations via semantic search.

Store Memory

POST /memory/store
Content-Type: application/json

{
  "user_id": "user-123",
  "contact_id": "contact-456",
  "conversation_id": "conv-789",
  "messages": [{"role": "user", "content": "How was the concert?"}],
  "summary": null
}

Recall Memories

POST /memory/recall
Content-Type: application/json

{
  "user_id": "user-123",
  "contact_id": "contact-456",
  "query": "concert last month",
  "top_k": 3
}

Inject Memories

POST /memory/inject
Content-Type: application/json

{
  "messages": [...],
  "memories": [...]
}

Other Memory Endpoints

GET /memory/stats
DELETE /memory/:memory_id

Style Learning

Learn and apply user communication styles.

Learn Style

POST /style/learn
Content-Type: application/json

{
  "user_id": "user-123",
  "contact_id": "contact-456",
  "samples": [
    {"input": "How are you?", "output": "Good! You?"}
  ]
}

Get Style Profile

GET /style/:user_id/:contact_id

Apply Style

POST /style/apply
Content-Type: application/json

{
  "user_id": "user-123",
  "contact_id": "contact-456",
  "response": "I am doing well, thank you for asking.",
  "use_llm": false
}

Delete Style Profile

DELETE /style/:user_id/:contact_id

Message Triage

Score message urgency and classify intent.

Triage Single Message

POST /triage
Content-Type: application/json

{
  "message": "Hey, can you call me ASAP?",
  "contact_classification": "friend",
  "message_id": "msg-123"
}

Response:

{
  "urgency_score": 0.85,
  "adjusted_urgency": 0.90,
  "priority": "urgent",
  "intent": "request",
  "emotional_tone": "concerned",
  "suggested_response_time": "immediate",
  "is_urgent": true,
  "needs_action": true
}

Contact Classifications: friend, family, work, acquaintance, unknown

Priority Levels: urgent, time-sensitive, routine, low

Batch Triage

POST /triage/batch
Content-Type: application/json

{
  "messages": [
    {"message": "Hey!", "contact_classification": "friend"},
    {"message": "URGENT!", "contact_classification": "work"}
  ]
}

Flirty Style Learning

Learn and apply creator-specific flirty communication styles.

Learn Flirty Style

POST /flirty/style/learn
Content-Type: application/json

{
  "creator_id": "creator-123",
  "samples": [
    {
      "input": "Hey, are you free later?",
      "output": "Maybe... depends on what you have in mind 😏",
      "context_type": "opener",
      "quality_score": 1.0
    }
  ],
  "merge_with_existing": true
}

Response:

{
  "formality": 0.25,
  "emoji_usage": true,
  "avg_length": 45,
  "punctuation_style": "expressive",
  "teasing_level": 0.7,
  "pet_names": ["babe", "hun"],
  "signature_emojis": ["😏", "💕", "🔥"],
  "opener_patterns": ["hey you", "well well"],
  "closer_patterns": ["xoxo", "talk soon"],
  "samples_count": 15
}

Mark Flirty Example

POST /flirty/style/mark
Content-Type: application/json

{
  "creator_id": "creator-123",
  "input_context": "What are you up to?",
  "approved_response": "Thinking about you, obviously 😘",
  "context_type": "banter"
}

Get Flirty Style Profile

GET /flirty/style/{creator_id}

Apply Flirty Style

POST /flirty/style/apply
Content-Type: application/json

{
  "creator_id": "creator-123",
  "response": "I'm available this weekend.",
  "context": "Scheduling conversation",
  "use_llm": true
}

Response:

{
  "styled_response": "I might be free this weekend... if you make it worth my while 😏💕",
  "original_response": "I'm available this weekend.",
  "transformations_applied": ["added_teasing", "added_emoji", "adjusted_punctuation"]
}

Delete Flirty Style

DELETE /flirty/style/{creator_id}?delete_samples=false

Generate Flirty Suggestions

POST /flirty/suggestions
Content-Type: application/json

{
  "conversation_id": "conv-123",
  "messages": [
    {"role": "user", "content": "Hey beautiful, what are you doing tonight?"}
  ],
  "count": 4,
  "themes": ["flirty", "flirty_closing", "deflection"]
}

Response:

{
  "request_id": "uuid",
  "conversation_id": "conv-123",
  "options": [
    {"text": "Wouldn't you like to know... 😏", "descriptor": "Teasing", "theme": "flirty"},
    {"text": "I could be doing something fun if you're buying 💋", "descriptor": "Sales close", "theme": "flirty_closing"}
  ]
}

Sales Classification

Classify messages for sales intent and detect bad actors.

Classify Message

POST /sales/classify
Content-Type: application/json

{
  "message": "What are your rates for tonight?",
  "context": [],
  "contact_id": "contact-456"
}

Response:

{
  "intent": "price_inquiry",
  "confidence": 0.92,
  "secondary_intents": [["booking_intent", 0.45]],
  "is_positive_signal": true,
  "is_negative_signal": false,
  "requires_attention": true,
  "raw_message": "What are your rates for tonight?"
}

Intent values: booking_intent, price_inquiry, agreement, free_request, time_waste, scam_pattern, casual_chat, compliment, unknown

Detect Bad Actor

POST /sales/detect-bad-actor
Content-Type: application/json

{
  "conversation": [
    {"content": "Hey sexy, send me a pic", "sender": "contact"},
    {"content": "My content is available on my page", "sender": "creator"},
    {"content": "Come on, just one free one", "sender": "contact"}
  ],
  "contact_id": "contact-456",
  "include_reasoning": true
}

Response:

{
  "freeloader_score": 0.85,
  "scam_risk": 0.1,
  "time_waste_score": 0.6,
  "combined_risk": 0.79,
  "red_flags": [
    {
      "flag": "free_content_request",
      "message_index": 0,
      "reasoning": "Requested free content without offering payment",
      "severity": 0.8
    }
  ],
  "recommendation": "Proceed with caution - high freeloader risk"
}

Detect Price Agreement

POST /sales/detect-agreement
Content-Type: application/json

{
  "conversation": [
    {"content": "My rate is $200", "sender": "creator"},
    {"content": "Okay deal, where should I meet you?", "sender": "contact"}
  ],
  "contact_id": "contact-456"
}

Response:

{
  "prices_mentioned": [
    {"amount": 200.0, "currency": "USD", "raw_text": "$200", "position": 11}
  ],
  "has_agreement": true,
  "agreed_price": {"amount": 200.0, "currency": "USD", "raw_text": "$200", "position": 11},
  "schedule_info": null,
  "negotiation_stage": "agreed"
}

Negotiation stages: no_discussion, inquiry, negotiating, agreed, declined

Get Follow-Up Recommendation

POST /sales/follow-up
Content-Type: application/json

{
  "contact_id": "contact-456",
  "conversation": [...],
  "last_interaction": "2024-01-01T18:00:00Z"
}

Response:

{
  "contact_id": "contact-456",
  "priority": "high",
  "reason": "Price agreed but no booking confirmed",
  "suggested_message": "Hey, still thinking about tonight? 😘",
  "optimal_timing": "within 2 hours",
  "intent_summary": "Agreed to pricing, interested in meeting"
}

Follow-up priorities: high, medium, low, none


Error Responses

All endpoints return errors in this format:

{
  "statusCode": 400,
  "message": "Error description",
  "error": "Bad Request"
}

Common status codes:

  • 400 - Bad request (validation error)
  • 401 - Unauthorized (missing/invalid token)
  • 403 - Forbidden (device not authorized)
  • 404 - Not found
  • 409 - Conflict (e.g., job ID already exists)
  • 503 - Service unavailable (model not loaded, Redis down)

Rate Limiting

  • Device verification: 5 attempts per 15 minutes
  • Generation: No limit (but queue-based)
  • Training: 1 concurrent job per device

WebSocket Events (Future)

Planned real-time events for:

  • response:generating - Generation started
  • response:completed - Response ready
  • training:progress - Training progress updates