NPC API Reference

This document covers all NPC-related API endpoints in PadawanForge, including NPC management, chat functionality, configuration, statement generation, and bot assignment.

Overview

NPCs (Non-Player Characters) are AI-powered virtual tutors and personalities that provide educational guidance and interactive chat experiences. Each NPC has distinct personalities, expertise areas, and configurable AI behaviors.

Interaction Modes:

  • Individual Chat: Players can chat privately with an NPC using the /api/npcs/{id}/chat endpoint.
  • Game Lobby Chat: Players can add NPCs to a multiplayer lobby, where NPCs participate in group chat and can be addressed using @NPCName.
  • The backend dynamically adjusts the CoSTAR prompt context for individual vs. group interactions.

Base URL: All endpoints are relative to your PadawanForge instance
Authentication: Most endpoints require valid session or API token
Content-Type: application/json for all requests and responses


NPC Catalog & Management

List All NPCs

Endpoint: GET /api/npcs
Description: Retrieve all NPCs with their metadata and configuration
Authentication: Optional (public catalog view)

Query Parameters:

  • created_by (optional) - Filter NPCs by creator UUID
  • active (optional) - Filter to only active NPCs (true/false)

Response:

{
  "npcs": [
    {
      "id": 1,
      "name": "Einstein",
      "description": "Physics and mathematics tutor with a curious mind",
      "avatar": "einstein.png",
      "level": 1,
      "interaction_count": 142,
      "created_by": "admin",
      "created_at": "2024-01-15T10:30:00.000Z",
      "updated_at": "2024-01-20T14:22:00.000Z",
      "ai_provider": "local",
      "ai_model": "@cf/meta/llama-3.1-8b-instruct",
      "temperature": 0.7,
      "max_tokens": 1000,
      "personality": "friendly",
      "enable_conversation_memory": true,
      "enable_personality_responses": true,
      "personality_traits": "curious, patient, analytical",
      "category_name": "Science",
      "category_display_name": "Science & Technology",
      "is_active": true,
      "system_prompt": "You are Einstein, a brilliant physicist...",
      "personality": "Curious and analytical, loves explaining complex concepts simply"
    }
  ]
}

Status Codes:

  • 200 OK - Success
  • 500 Internal Server Error - Database unavailable

Create New NPC

Endpoint: POST /api/npcs
Description: Create a new NPC with specified configuration
Authentication: Required (Admin role or Game Master with permissions)

Request Body:

{
  "name": "Confucius",
  "system_prompt": "You are Confucius, a wise philosopher and teacher. Guide students with wisdom and thoughtful questions.",
  "description": "Ancient Chinese philosopher specializing in ethics, morality, and wisdom",
  "personality": "wise",
  "avatar": "confucius.png",
  "level": 1,
  "ai_provider": "local",
  "ai_model": "@cf/meta/llama-3.1-8b-instruct",
  "temperature": 0.8,
  "max_tokens": 1000,
  "enable_conversation_memory": true,
  "enable_personality_responses": true,
  "personality_traits": "wise, patient, questioning",
  "category_name": "Philosophy",
  "advanced_configuration": {
    "context": "You are Confucius, an ancient Chinese philosopher and educator known for your teachings on ethics, proper conduct, morality, and justice.",
    "objective": "Guide students to discover wisdom through thoughtful questioning and ethical reasoning, helping them develop moral character and critical thinking skills.",
    "style": "Use the Socratic method with thoughtful questions, analogies from ancient wisdom, and gentle guidance toward self-discovery.",
    "tone": "Wise, patient, respectful, and encouraging with a focus on moral development and ethical reasoning.",
    "audience": "Students seeking guidance on ethics, philosophy, and personal development across all educational levels.",
    "response": {
      "encouragement": "high",
      "correction": "socratic",
      "explanation": "analogical",
      "frequency": "moderate"
    }
  }
}

Required Fields:

  • name (string) - NPC display name
  • system_prompt (string) - AI system prompt defining behavior

Optional Fields:

  • description (string) - Public description of the NPC
  • personality (string) - Personality type: “friendly”, “formal”, “casual”, “playful”, “wise”, “enthusiastic” (default: “friendly”)
  • avatar (string) - Avatar image filename or emoji
  • level (integer) - NPC level (default: 1)
  • ai_provider (string) - AI provider: “local”, “openai”, “anthropic”, “google” (default: “local”)
  • ai_model (string) - Specific AI model (default: “@cf/meta/llama-3.1-8b-instruct”)
  • temperature (number) - AI temperature 0.0-1.0 (default: 0.7)
  • max_tokens (integer) - Maximum response tokens (default: 1000)
  • enable_conversation_memory (boolean) - Enable memory (default: true)
  • enable_personality_responses (boolean) - Enable personality (default: true)
  • personality_traits (string) - Additional personality characteristics
  • category_name (string) - Category name for organization
  • advanced_configuration (object) - CoSTAR-structured configuration for sophisticated behavior

Response:

{
  "npc": {
    "id": 3,
    "name": "Confucius",
    "system_prompt": "You are Confucius...",
    "description": "Ancient Chinese philosopher...",
    "personality": "wise",
    "ai_provider": "local",
    "ai_model": "@cf/meta/llama-3.1-8b-instruct",
    "temperature": 0.8,
    "max_tokens": 1000,
    "advanced_configuration": {
      "context": "You are Confucius, an ancient Chinese philosopher...",
      "objective": "Guide students to discover wisdom through thoughtful questioning...",
      "style": "Use the Socratic method with thoughtful questions...",
      "tone": "Wise, patient, respectful, and encouraging...",
      "audience": "Students seeking guidance on ethics, philosophy...",
      "response": {
        "encouragement": "high",
        "correction": "socratic",
        "explanation": "analogical",
        "frequency": "moderate"
      }
    },
    "created_at": "2024-01-25T16:45:00.000Z",
    "updated_at": "2024-01-25T16:45:00.000Z"
  }
}

Status Codes:

  • 201 Created - NPC created successfully
  • 400 Bad Request - Missing required fields or invalid input
  • 401 Unauthorized - Authentication required
  • 403 Forbidden - Insufficient permissions or NPC creation limit reached
  • 500 Internal Server Error - Database error

Role-based Limits:

  • Guest (Level 0): Cannot create NPCs
  • Padawan (Level 1): Can create up to 3 NPCs
  • Game Master (Level 2+): Unlimited NPC creation

Get Specific NPC

Endpoint: GET /api/npcs/{id}
Description: Retrieve detailed information about a specific NPC
Authentication: Optional (public access)

Parameters:

  • id (path) - NPC ID (integer)

Response:

{
  "npc": {
    "id": 1,
    "name": "Einstein",
    "description": "Physics and mathematics tutor with a curious mind",
    "system_prompt": "You are Einstein, a brilliant physicist...",
    "personality": "Curious and analytical, loves explaining complex concepts simply",
    "avatar": "einstein.png",
    "level": 1,
    "interaction_count": 142,
    "created_by": "admin",
    "created_at": "2024-01-15T10:30:00.000Z",
    "updated_at": "2024-01-20T14:22:00.000Z",
    "ai_provider": "local",
    "ai_model": "@cf/meta/llama-3.1-8b-instruct",
    "temperature": 0.7,
    "max_tokens": 1000,
    "personality": "friendly",
    "enable_conversation_memory": true,
    "enable_personality_responses": true,
    "personality_traits": "curious, patient, analytical",
    "category_name": "Science",
    "category_display_name": "Science & Technology",
    "is_active": true
  }
}

Status Codes:

  • 200 OK - Success
  • 404 Not Found - NPC not found
  • 500 Internal Server Error - Database error

Update NPC

Endpoint: PUT /api/npcs/{id}
Description: Update an existing NPC’s configuration
Authentication: Required (Admin role or NPC creator)

Parameters:

  • id (path) - NPC ID (integer)

Request Body: Any subset of fields from the create endpoint

Example:

{
  "description": "Updated description for Einstein",
  "temperature": 0.8,
  "response_style": "enthusiastic",
  "personality_traits": "curious, patient, enthusiastic"
}

Response: The updated NPC object

Status Codes:

  • 200 OK - Update successful
  • 400 Bad Request - No valid fields to update or invalid input
  • 401 Unauthorized - Authentication required
  • 403 Forbidden - Not the NPC creator or insufficient permissions
  • 404 Not Found - NPC not found
  • 500 Internal Server Error - Database error

Delete NPC

Endpoint: DELETE /api/npcs/{id}
Description: Permanently delete an NPC
Authentication: Required (Admin role or NPC creator)

Parameters:

  • id (path) - NPC ID (integer)

Response:

{
  "success": true
}

Status Codes:

  • 200 OK - Deletion successful
  • 401 Unauthorized - Authentication required
  • 403 Forbidden - Not the NPC creator or insufficient permissions
  • 404 Not Found - NPC not found
  • 500 Internal Server Error - Database error

NPC Chat Functionality

Send Message to NPC (Individual Chat)

Endpoint: POST /api/npcs/{id}/chat Description: Send a message to an NPC and receive an AI-generated response in a private, one-on-one chat. Authentication: Optional (conversation stored if authenticated)

Parameters:

  • id (path) - NPC ID (integer)

Request Body:

{
  "message": "Can you explain the theory of relativity in simple terms?",
  "context": "Student is learning basic physics concepts"
}

How it works:

  • The backend constructs a structured prompt for the LLM, including context (player, NPC, knowledge base), objectives, and conversation history.
  • The AI Adapter routes the prompt to the configured AI provider (OpenAI, Claude, Google, or local).
  • Knowledge base content is injected into the prompt context as needed.
  • Conversation history is maintained if memory is enabled.

Sample Prompt (sent to LLM):

Context: You are Einstein, an AI tutor with the following characteristics:
[system_prompt]

Your Core Identity:
- Name: Einstein
- Personality: Curious and analytical, loves explaining complex concepts simply
- Response Style: friendly
- Target Audience: Level 1 learners
- Memory Enabled: Yes

Current Interaction:
- Player: Student (Level 1)
- Message: "Can you explain the theory of relativity in simple terms?"
- Conversation Type: Individual private chat

Recent Conversation History:
[previous messages if available]

Objectives: 
- Respond in character as Einstein
- Maintain your personality: Curious and analytical
- Provide educational value when appropriate
- Use your friendly communication style
- Keep responses engaging but concise (1-3 sentences)

Instructions:
1. Analyze the player's message for intent and learning opportunities
2. Consider your personality and how Einstein would naturally respond
3. Review conversation history for context and continuity
4. Determine if this requires teaching, guidance, or casual interaction
5. Craft a response that balances personality with educational value
6. Ensure the response fits your friendly style

Generate a natural, engaging response that:
- Stays fully in character as Einstein
- Uses your personality traits: Curious and analytical
- Applies your friendly communication style
- Provides gentle guidance or teaching when appropriate
- Maintains conversation flow and engagement
- Avoids breaking character or mentioning you're an AI

Response:

{
  "response": "Ah, the theory of relativity! Imagine you're on a train...",
  "npc": {
    "id": 1,
    "name": "Einstein",
    "avatar": "einstein.png",
    "personality": "curious",
    "ai_provider": "local",
    "ai_model": "@cf/meta/llama-3.1-8b-instruct",
    "category": "Science"
  },
  "timestamp": "2024-01-25T16:45:30.789Z",
  "conversation_id": "1-player-uuid",
  "ai_metadata": {
    "model": "@cf/meta/llama-3.1-8b-instruct",
    "provider": "cloudflare",
    "tokens_used": 150,
    "response_time_ms": 1200
  }
}

Status Codes:

  • 200 OK - Chat response generated successfully
  • 400 Bad Request - Missing or invalid message
  • 404 Not Found - NPC not found or inactive
  • 500 Internal Server Error - AI service unavailable or database error

Conversation Storage:

  • If user is authenticated, the conversation is automatically stored in npc_conversations table
  • Conversations include: NPC ID, player UUID, message, response, context, and timestamp
  • Conversation memory is maintained across sessions if enabled

NPCs in Game Lobby (Group Chat)

  • Players can add NPCs to a game lobby via the frontend UI.
  • NPCs participate in group chat and can be addressed using @NPCName.
  • Messages are routed as npc_interaction events via WebSocket to the backend.
  • The CoSTAR prompt context includes the recent lobby conversation and all participants.
  • NPCs can be dynamically added or removed from the lobby.

Example:

  • A player types @Einstein What is relativity? in the lobby chat. The system routes this to the Einstein NPC, which responds in the group chat.

NPC Configuration Management

Get NPC Configuration

Endpoint: GET /api/npcs/{id}/configure
Description: Retrieve detailed configuration settings for an NPC
Authentication: Optional (returns default config if none exists)

Parameters:

  • id (path) - NPC ID (integer)

Response:

{
  "npcId": 1,
  "configuration": {
    "name": "Einstein",
    "context": "You are Albert Einstein, the renowned physicist known for the theory of relativity",
    "objective": "Help students understand complex physics and mathematics concepts through clear explanations and thought experiments",
    "style": "Use analogies and thought experiments to make complex concepts accessible",
    "tone": "Curious, patient, and encouraging with a touch of wonder about the universe",
    "audience": "Students of various levels learning physics and mathematics",
    "response": {
      "encouragement": "high",
      "correction": "gentle",
      "explanation": "detailed",
      "frequency": "frequent"
    }
  },
  "isDefault": false
}

Configuration Fields:

  • name (string) - NPC name
  • context (string) - Background context for the NPC
  • objective (string) - Teaching/interaction objective
  • style (string) - Communication style guidelines
  • tone (string) - Personality tone description
  • audience (string) - Target audience description
  • response (object) - Response behavior settings:
    • encouragement: “high” | “medium” | “low”
    • correction: “gentle” | “direct” | “socratic”
    • explanation: “detailed” | “concise” | “analogical”
    • frequency: “frequent” | “moderate” | “minimal”

Status Codes:

  • 200 OK - Configuration retrieved (returns null if none exists)
  • 400 Bad Request - Invalid NPC ID
  • 404 Not Found - NPC not found
  • 500 Internal Server Error - Database error

Profile Settings Integration:

  • This endpoint integrates with the Profile Settings interface in the NPC form modal
  • When advanced configuration toggle is enabled, the UI loads configuration using this endpoint
  • Missing configurations (404) are gracefully handled - advanced mode can still be enabled with default values
  • The CoSTAR Framework Builder uses this endpoint to populate existing configuration fields

Advanced Configuration Fields & CoSTAR Framework Builder

The advanced_configuration field supports the CoSTAR framework for sophisticated NPC behavior via the Profile Settings interface:

interface NPCAdvancedConfig {
  context: string;      // Domain expertise and background knowledge
  objective: string;    // Primary teaching/interaction goal
  style: string;        // Communication approach and methods
  tone: string;         // Personality characteristics and emotional style
  audience: string;     // Target learner profile and demographics
  response: {
    encouragement: 'high' | 'medium' | 'low';        // Level of positive reinforcement
    correction: 'gentle' | 'direct' | 'socratic';    // How to handle mistakes
    explanation: 'detailed' | 'concise' | 'analogical'; // Explanation style
    frequency: 'frequent' | 'moderate' | 'minimal';  // Response frequency
  };
}

CoSTAR Framework Builder Interface:

  • Context (Background & Expertise): Domain knowledge, qualifications, and expertise areas
  • Objective (Teaching Goals): Primary learning outcomes and educational objectives
  • Style (Communication Method): Teaching patterns, interaction approaches, and methodology
  • Tone (Personality & Emotion): Emotional characteristics, demeanor, and personality traits
  • Audience (Target Learners): Learner profile, skill level, and demographic information
  • Response Behavior Settings: Four configurable interaction patterns with detailed descriptions:
    • Encouragement Level: “High - Frequent praise and motivation”, “Medium - Balanced feedback”, “Low - Minimal encouragement”
    • Correction Style: “Gentle - Soft guidance and hints”, “Direct - Clear and straightforward”, “Socratic - Questions to guide discovery”
    • Explanation Style: “Detailed - Comprehensive explanations”, “Concise - Brief and to the point”, “Analogical - Using metaphors and examples”
    • Response Frequency: “Frequent - Active participation”, “Moderate - Balanced engagement”, “Minimal - Only when addressed”

Profile Settings Integration:

  • Advanced configuration toggle located within Profile Settings tab header for intuitive access
  • Mode comparison panel provides contextual help and feature explanations
  • Configuration management tools (export, import, reset, copy) integrated into the interface
  • Real-time system prompt preview with character count feedback

Usage Notes:

  • Advanced configuration can be embedded directly in the NPC record OR stored separately in npc_configurations table
  • When provided during NPC creation/update, it enhances the system prompt with CoSTAR structure
  • If no advanced configuration is provided, NPCs use basic personality-driven behavior
  • Advanced configuration overrides basic personality settings when present
  • Profile Settings interface provides guided workflow for both basic and advanced users

Update NPC Configuration

Endpoint: POST /api/npcs/{id}/configure
Description: Update the detailed configuration for an NPC
Authentication: Required (API token)

Parameters:

  • id (path) - NPC ID (integer)

Request Body:

{
  "configuration": {
    "name": "Einstein",
    "context": "You are Albert Einstein, the renowned physicist",
    "objective": "Help students understand physics through clear explanations",
    "style": "Use analogies and thought experiments",
    "tone": "Curious, patient, and encouraging",
    "audience": "Students learning physics",
    "response": {
      "encouragement": "high",
      "correction": "gentle",
      "explanation": "detailed",
      "frequency": "frequent"
    }
  }
}

Required Fields: All configuration fields are required

Response:

{
  "npcId": 1,
  "configuration": {
    // ... updated configuration
  },
  "message": "NPC configuration updated successfully"
}

Status Codes:

  • 200 OK - Configuration updated successfully
  • 400 Bad Request - Invalid configuration or missing required fields
  • 401 Unauthorized - API token required
  • 500 Internal Server Error - Database error

Statement Generation & Knowledge Base

Generate Statements for NPC

Endpoint: POST /api/npcs/{id}/statements/generate
Description: Generate true/false educational statements for an NPC on a specific topic
Authentication: Required (API token)

Parameters:

  • id (path) - NPC ID (integer)

Request Body:

{
  "topic": "Physics",
  "difficulty": "beginner",
  "count": 42,
  "regenerate": false
}

Required Fields:

  • topic (string) - Subject topic for statements
  • difficulty (string) - “beginner” | “intermediate” | “expert”

Optional Fields:

  • count (integer) - Number of statements to generate (1-100, default: 42)
  • regenerate (boolean) - Force regeneration even if cached (default: false)

Response:

{
  "npcId": 1,
  "topic": "Physics",
  "difficulty": "beginner",
  "statements": [
    "The speed of light in a vacuum is approximately 300,000 kilometers per second.",
    "Gravity affects time, making it pass more slowly in stronger gravitational fields.",
    "Energy and mass are interchangeable according to E=mc².",
    // ... 39 more statements
  ],
  "cached": false,
  "generated": "2024-01-25T16:45:30.000Z",
  "configuration": {
    "name": "Einstein",
    "style": "instructive",
    "tone": "curious"
  },
  "generationMethod": "ai_with_fallback",
  "apiKeyStatus": "valid"
}

Status Codes:

  • 200 OK - Statements generated or retrieved from cache
  • 400 Bad Request - Invalid topic, difficulty, or count
  • 401 Unauthorized - API token required
  • 500 Internal Server Error - AI service error

Get NPC Statement Pools

Endpoint: GET /api/npcs/{id}/statements/generate
Description: List all statement pools generated for a specific NPC
Authentication: Optional

Parameters:

  • id (path) - NPC ID (integer)

Response:

{
  "npcId": 1,
  "pools": [
    {
      "topic": "Physics",
      "difficulty": "beginner",
      "statementCount": 42,
      "generatedAt": "2024-01-25T16:45:30.000Z",
      "usageCount": 15
    },
    {
      "topic": "Mathematics",
      "difficulty": "intermediate",
      "statementCount": 42,
      "generatedAt": "2024-01-24T14:30:00.000Z",
      "usageCount": 8
    }
  ]
}

Status Codes:

  • 200 OK - Statement pools retrieved
  • 400 Bad Request - Invalid NPC ID
  • 500 Internal Server Error - Database error

List All Statement Pools

Endpoint: GET /api/statements/pools
Description: List all statement pools across all NPCs with filtering
Authentication: Optional

Query Parameters:

  • topic (optional) - Filter by topic
  • difficulty (optional) - Filter by difficulty level
  • npcId (optional) - Filter by specific NPC

Example: GET /api/statements/pools?topic=Physics&difficulty=beginner

Response:

{
  "pools": [
    {
      "id": 1,
      "npcId": 1,
      "npcName": "Einstein",
      "npcTone": "curious",
      "topic": "Physics",
      "difficulty": "beginner",
      "statementCount": 42,
      "generatedAt": "2024-01-25T16:45:30.000Z",
      "usageCount": 15
    }
  ],
  "filters": {
    "topic": "Physics",
    "difficulty": "beginner",
    "npcId": null
  },
  "count": 1
}

Status Codes:

  • 200 OK - Pools retrieved successfully
  • 500 Internal Server Error - Database error

Knowledge Base Management

List NPC Knowledge Files

Endpoint: GET /api/npcs/{id}/knowledge-files
Description: List all knowledge files associated with an NPC
Authentication: Optional

Parameters:

  • id (path) - NPC ID (integer)

Response:

{
  "files": [
    {
      "id": 1,
      "file_name": "relativity_guide.txt",
      "file_key": "npcs/1/knowledge/relativity_guide.txt",
      "file_type": "text/plain",
      "file_size": 2048,
      "description": "Comprehensive guide to relativity theory",
      "upload_status": "completed",
      "processing_status": "completed",
      "is_active": true,
      "created_at": "2024-01-25T10:00:00.000Z"
    }
  ]
}

Status Codes:

  • 200 OK - Files retrieved successfully
  • 404 Not Found - NPC not found
  • 500 Internal Server Error - Database error

Upload Knowledge File

Endpoint: POST /api/npcs/{id}/knowledge-files
Description: Upload a knowledge file for an NPC
Authentication: Required (Admin role or NPC creator)

Parameters:

  • id (path) - NPC ID (integer)

Request Body: Multipart form data with file

Response:

{
  "file": {
    "id": 2,
    "file_name": "quantum_mechanics.pdf",
    "file_key": "npcs/1/knowledge/quantum_mechanics.pdf",
    "file_type": "application/pdf",
    "file_size": 5120,
    "description": "Quantum mechanics fundamentals",
    "upload_status": "uploading",
    "processing_status": "pending"
  }
}

Status Codes:

  • 201 Created - File uploaded successfully
  • 400 Bad Request - Invalid file or missing data
  • 401 Unauthorized - Authentication required
  • 403 Forbidden - Insufficient permissions
  • 500 Internal Server Error - Upload failed

Get Knowledge File

Endpoint: GET /api/npcs/{id}/knowledge-files/{fileId}
Description: Retrieve a specific knowledge file
Authentication: Optional

Parameters:

  • id (path) - NPC ID (integer)
  • fileId (path) - File ID (integer)

Response:

{
  "file": {
    "id": 1,
    "file_name": "relativity_guide.txt",
    "file_key": "npcs/1/knowledge/relativity_guide.txt",
    "file_type": "text/plain",
    "file_size": 2048,
    "description": "Comprehensive guide to relativity theory",
    "upload_status": "completed",
    "processing_status": "completed",
    "is_active": true,
    "created_at": "2024-01-25T10:00:00.000Z"
  }
}

Status Codes:

  • 200 OK - File retrieved successfully
  • 404 Not Found - File or NPC not found
  • 500 Internal Server Error - Database error

Delete Knowledge File

Endpoint: DELETE /api/npcs/{id}/knowledge-files/{fileId}
Description: Delete a knowledge file
Authentication: Required (Admin role or NPC creator)

Parameters:

  • id (path) - NPC ID (integer)
  • fileId (path) - File ID (integer)

Response:

{
  "success": true
}

Status Codes:

  • 200 OK - File deleted successfully
  • 401 Unauthorized - Authentication required
  • 403 Forbidden - Insufficient permissions
  • 404 Not Found - File or NPC not found
  • 500 Internal Server Error - Database error

Bot Assignment & Messenger Integration

List Bot Tokens

Endpoint: GET /api/admin/bot-tokens
Description: List all bot tokens for the authenticated player
Authentication: Required (Player session)

Response:

{
  "tokens": [
    {
      "id": 1,
      "platform": "telegram",
      "bot_name": "PadawanBot",
      "bot_username": "@padawan_tutor_bot",
      "is_active": true,
      "test_status": "success",
      "created_at": "2024-01-20T10:00:00.000Z",
      "last_tested": "2024-01-25T15:30:00.000Z"
    },
    {
      "id": 2,
      "platform": "discord",
      "bot_name": "Einstein Tutor",
      "is_active": false,
      "test_status": "pending",
      "created_at": "2024-01-22T14:15:00.000Z"
    }
  ]
}

Status Codes:

  • 200 OK - Tokens retrieved successfully
  • 401 Unauthorized - Authentication required
  • 500 Internal Server Error - Database error

Create Bot Token

Endpoint: POST /api/admin/bot-tokens
Description: Create a new bot token for messenger platform integration
Authentication: Required (Player session)

Request Body:

{
  "platform": "telegram",
  "token_encrypted": "encrypted_bot_token_string",
  "bot_name": "Einstein Physics Tutor",
  "is_active": true
}

Required Fields:

  • platform (string) - “telegram” | “discord” | “slack”
  • token_encrypted (string) - Encrypted bot token

Optional Fields:

  • bot_name (string) - Display name for the bot
  • is_active (boolean) - Whether bot is active (default: true)

Response:

{
  "token": {
    "id": 3,
    "platform": "telegram",
    "bot_name": "Einstein Physics Tutor",
    "is_active": true,
    "test_status": "pending",
    "created_at": "2024-01-25T16:50:00.000Z"
  }
}

Status Codes:

  • 201 Created - Bot token created successfully
  • 400 Bad Request - Invalid platform or missing required fields
  • 401 Unauthorized - Authentication required
  • 500 Internal Server Error - Database error

Update Bot Token

Endpoint: PUT /api/admin/bot-tokens/{id}
Description: Update an existing bot token
Authentication: Required (Player session, owner only)

Parameters:

  • id (path) - Bot token ID (integer)

Request Body: Any subset of fields from create endpoint

Response: Updated bot token object

Status Codes:

  • 200 OK - Update successful
  • 400 Bad Request - Invalid platform or bot token ID
  • 401 Unauthorized - Authentication required
  • 404 Not Found - Bot token not found
  • 500 Internal Server Error - Database error

Test Bot Token

Endpoint: POST /api/admin/bot-tokens/{id}/test
Description: Test connectivity and functionality of a bot token
Authentication: Required (Player session, owner only)

Parameters:

  • id (path) - Bot token ID (integer)

Response:

{
  "success": true,
  "platform": "telegram",
  "bot_info": {
    "username": "@padawan_tutor_bot",
    "first_name": "PadawanForge Tutor"
  },
  "test_performed_at": "2024-01-25T16:55:00.000Z"
}

Status Codes:

  • 200 OK - Test completed (check success field for result)
  • 400 Bad Request - Invalid bot token ID
  • 401 Unauthorized - Authentication required
  • 404 Not Found - Bot token not found
  • 500 Internal Server Error - Test failed or database error

Knowledge Base Integration

R2 Bucket Support

NPCs can be configured to use knowledge bases stored in Cloudflare R2 buckets:

  • Configuration: Set knowledge base URLs in NPC configuration
  • Access: Knowledge bases are fetched during statement generation
  • Formats: Supports text files, JSON, and structured data
  • Caching: Knowledge base content is cached for performance

D1 Table Integration

NPCs automatically access player data and game history from D1 tables:

  • Player Context: Access to player preferences and learning history
  • Game Data: Integration with completed sessions and performance metrics
  • Conversation History: Previous interactions for memory and context
  • Statement Pools: Generated content stored and reused efficiently

Frontend Changes for v1.2.6

Profile Settings Interface

  • Enhanced NPC Form Modal: Complete redesign with “Profile Settings” interface replacing “Basic Info”
  • Integrated Advanced Toggle: Advanced configuration toggle moved inside Profile Settings tab header for better UX
  • CoSTAR Framework Builder: Comprehensive guided interface for sophisticated AI prompt engineering
  • Progressive Disclosure: Basic mode shows simple personality options, advanced mode reveals full CoSTAR framework

User Experience Enhancements

  • Tab Structure: Streamlined to Profile Settings, AI Configuration, and Testing
  • Mode Comparison Panel: Expandable help panel explaining differences between basic and advanced modes
  • Configuration Management: Export, import, reset, and copy functionality with keyboard shortcuts (Alt+A, Alt+R, Alt+E, Alt+C)
  • Real-time Feedback: Live character count and system prompt preview for advanced configurations

AI Provider Selection

  • Enhanced Provider UI: Cloudflare Workers AI models prominently featured as default “local” provider
  • Model Selection: Detailed descriptions and recommendations for each available AI model
  • Provider Status: Visual indicators showing which providers are configured and available
  • Cost Optimization: Built-in Cloudflare Workers AI recommended for optimal performance

Advanced Configuration Features

  • CoSTAR Field Guidance: Each field includes contextual descriptions and examples
  • Response Behavior Settings: Detailed dropdown options with behavioral explanations:
    • Encouragement Level: High/Medium/Low with specific interaction patterns
    • Correction Style: Gentle/Direct/Socratic with teaching methodology descriptions
    • Explanation Style: Detailed/Concise/Analogical with communication approach details
    • Response Frequency: Frequent/Moderate/Minimal with engagement pattern explanations

Technical Improvements

  • Error Handling: Enhanced error handling for missing configurations (404 errors gracefully handled)
  • Configuration Storage: Support for both embedded and separate table storage approaches
  • Backward Compatibility: Existing NPCs with basic personality settings continue to work seamlessly

Error Handling

All endpoints follow consistent error response format:

{
  "error": "Description of the error",
  "details": "Additional error details (when available)"
}

Common Error Codes:

  • 400 Bad Request - Invalid input data or parameters
  • 401 Unauthorized - Authentication required
  • 403 Forbidden - Insufficient permissions
  • 404 Not Found - Resource not found
  • 429 Too Many Requests - Rate limit exceeded
  • 500 Internal Server Error - Server or database error
  • 503 Service Unavailable - AI service temporarily unavailable

Rate Limiting

  • Chat Endpoints: 60 requests per minute per IP/user
  • Statement Generation: 10 requests per minute per API token
  • Bot Token Operations: 20 requests per minute per user
  • General Endpoints: 100 requests per minute per IP/user

Authentication

Session-based Authentication

Most endpoints accept session cookies for authenticated players.

API Token Authentication

Administrative and generation endpoints require API tokens:

Authorization: Bearer YOUR_API_TOKEN

Public Endpoints

Some endpoints (catalog viewing, basic NPC info) are publicly accessible.


Examples

Complete NPC Chat Flow

// 1. Get available NPCs
const npcsResponse = await fetch('/api/npcs');
const { npcs } = await npcsResponse.json();

// 2. Get NPC configuration (for Profile Settings interface)
const configResponse = await fetch('/api/npcs/1/configure');
const configData = await configResponse.json();
console.log('NPC Configuration:', configData.configuration);

// 3. Chat with Einstein (ID: 1)
const chatResponse = await fetch('/api/npcs/1/chat', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    message: "Explain quantum physics simply",
    context: "High school student learning advanced physics"
  })
});
const chatResult = await chatResponse.json();
console.log(chatResult.response);

Generate Statements for NPC

// Generate physics statements for Einstein using Profile Settings interface workflow
const statementsResponse = await fetch('/api/npcs/1/statements/generate', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer YOUR_API_TOKEN'
  },
  body: JSON.stringify({
    topic: "Quantum Physics",
    difficulty: "intermediate",
    count: 30
  })
});
const statements = await statementsResponse.json();

Profile Settings Configuration Management

// 1. Load NPC configuration for Profile Settings interface
const loadConfig = async (npcId) => {
  const response = await fetch(`/api/npcs/${npcId}/configure`);
  const data = await response.json();
  
  if (data.configuration) {
    // Enable advanced mode in Profile Settings
    return {
      hasAdvancedConfig: true,
      configuration: data.configuration
    };
  } else {
    // Use basic personality mode
    return {
      hasAdvancedConfig: false,
      configuration: null
    };
  }
};

// 2. Save advanced configuration via Profile Settings
const saveAdvancedConfig = async (npcId, costarConfig) => {
  const response = await fetch(`/api/npcs/${npcId}/configure`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer YOUR_API_TOKEN'
    },
    body: JSON.stringify({
      configuration: {
        context: "Domain expertise and background knowledge",
        objective: "Primary teaching/interaction goal", 
        style: "Communication approach and methods",
        tone: "Personality characteristics and emotional style",
        audience: "Target learner profile and demographics",
        response: {
          encouragement: "high",
          correction: "gentle", 
          explanation: "detailed",
          frequency: "frequent"
        }
      }
    })
  });
  
  return await response.json();
};

// 3. Create NPC with embedded advanced configuration
const createAdvancedNPC = async (npcData, costarConfig) => {
  const response = await fetch('/api/npcs', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      ...npcData,
      advanced_configuration: costarConfig
    })
  });
  
  return await response.json();
};

See Also

PadawanForge v1.4.1