twofourlabs/agent-docs/ai-integrated-api-backend

Trust tier 3
  • community
Source check pending

Checking that the SKILL.md file is still in the repository.

Comprehensive guide for building production-grade AI-integrated backends with multi-provider support, intelligent fallback mechanisms, region configuration, prompt management with variables/tools, and session-based billing. Use when implementing AI features in Django/Python backends or designing LLM-powered API architectures with external data integration.

Install

npx vskill@latest install twofourlabs/agent-docs/ai-integrated-api-backend

SKILL.md

<objective> This skill provides exhaustive knowledge for building robust, production-grade AI-integrated backend systems featuring:

  • Multi-Provider Architecture: OpenAI, Anthropic, Gemini, AWS Bedrock, Byteplus, OpenRouter with seamless switching
  • Intelligent Fallbacks: Automatic degradation chains (e.g., GPT-4 → Claude → Gemini-Flash)
  • Region-Based Routing: AWS Bedrock multi-region support, geographic failover
  • Advanced Prompt Management: Template-driven prompts with {{variable}} substitution, function mapping, YAML-structured instructions
  • External API Integration: Weather, astrology, finance APIs → AI transformation pipelines
  • Session & Billing: Per-message charging, wallet deduction, price locking
  • Gateway Pattern: JWT-authenticated internal LLM gateway for centralized AI access

</objective>

<essential_principles>

Core Architecture Principles

1. Multi-Provider Design Philosophy

  • Never depend on a single AI provider; always maintain fallback chains
  • Design provider-agnostic interfaces that abstract vendor-specific implementations
  • Implement graceful degradation when premium models fail (e.g., GPT-4 → GPT-3.5 → Gemini-Flash)
  • Use configuration-driven provider selection, not hardcoded logic
  • Support multiple providers simultaneously (A/B testing, cost optimization)

2. Separation of Concerns

  • Models Layer: Database models for bots, LLM configs, prompts, sessions (Django ORM)
  • Services Layer: Provider-specific integrations (OpenAI, Anthropic, Gemini, Bedrock, etc.)
  • Helpers Layer: Business logic for prompt rendering, fallback routing, response handling
  • Gateway Layer: Central JWT-authenticated service for LLM API access
  • API Layer: External API managers for weather, astrology, finance data

3. Configuration Over Code

  • Store LLM configurations (provider, model, temperature, tokens) in database
  • Enable A/B testing by switching active configurations without code deployments
  • Support per-bot customization of AI behavior through metadata fields
  • Use is_active flag to switch between configurations instantly

4. Prompt Engineering Best Practices

  • Template-driven prompts with variable substitution ({{variable_name}})
  • Centralized prompt management separate from business logic
  • Support for system-level variables ({{current_date}}, {{current_time}}) and user-level variables ({{user_name}}, {{user_age}})
  • YAML-based structured prompts for complex multi-section instructions
  • Function mapping for dynamic variable resolution

5. Fallback & Resilience

  • Every provider has a fallback chain ending in a reliable universal fallback (e.g., Gemini-Flash)
  • Fallbacks inherit system instructions and region configurations
  • Support provider-specific fallbacks (e.g., Gemini Pro → Gemini Flash) and cross-provider fallbacks
  • Region-aware fallbacks for AWS Bedrock (ap-south-1, us-east-1, etc.)

6. Security & Authentication

  • JWT tokens for internal LLM gateway authentication
  • Token caching to reduce overhead (cache duration: token expiry - 2 seconds)
  • API key management from environment variables
  • Service-to-service authentication with signed payloads

</essential_principles>

<system_architecture>

High-Level Data Flow

Full Request Flow (External API → AI → Response)
User Request (Chat Message)
↓
API Endpoint (validate input, check session)
↓
Session Manager (create/resume session, lock pricing)
↓
External API Layer (if needed: fetch astrology, weather, etc.)
├─→ Cache Check (multi-layer: instance → distributed → database)
├─→ External API Call (if cache miss)
└─→ Data Transformation Pipeline (validate → normalize → enrich → format)
↓
Prompt Builder
├─→ Load Bot LLM Config (model, provider, temperature, metadata)
├─→ Render Prompt Template (replace {{variables}} with actual values)
├─→ Assemble Context (user data + external data + history)
└─→ Build Final Prompt (YAML or JSON structured)
↓
LLM Gateway Manager
├─→ Get/Generate JWT Token (cached)
├─→ Build Fallback Chain (provider-specific + universal)
└─→ POST to Internal Gateway (/v1/generate/)
↓
Internal LLM Gateway (separate service)
├─→ Validate JWT
├─→ Route to Primary Provider (OpenAI, Anthropic, Gemini, Bedrock, etc.)
├─→ On Failure: Try Fallback 1
├─→ On Failure: Try Fallback 2
└─→ On Failure: Universal Fallback (Gemini-Flash)
↓
Response Processing
├─→ Parse LLM Response
├─→ Validate Output
└─→ Store in Database
↓
Billing (if session-based)
├─→ Calculate Units (tokens, messages, minutes)
├─→ Check Wallet Balance
├─→ Deduct Amount
└─→ Log Transaction
↓
Save to Database (conversation history)
↓
Return to User (API response)
Multi-Provider Routing with Fallbacks
Request → Load BotLLMConfig → Determine Primary Provider
↓
Primary: Gemini 2.5-Pro
├─→ Fallback 1: Gemini 2.5-Flash
├─→ Fallback 2: Gemini 2.0-Flash
└─→ Universal Fallback: Gemini 2.0-Flash
Primary: AWS Bedrock Deepseek-v3 (region: ap-south-1)
├─→ Fallback 1: Byteplus Deepseek-v3
├─→ Fallback 2: Gemini 2.0-Flash (region-agnostic)
└─→ Universal Fallback: Gemini 2.0-Flash
Primary: Byteplus
├─→ Fallback 1: Gemini 2.0-Flash
└─→ Universal Fallback: Gemini 2.0-Flash

</system_architecture>

<domain_knowledge_index> All implementation details, code examples, and architectural patterns are organized below:

System Architecture:

  • Multi-Provider Architecture (see <multi_provider_architecture>)
  • Database Schema for Bots, LLM Configs (see <database_schema>)
  • LLM Gateway Pattern with JWT (see <gateway_pattern>)

Provider Integration:

  • Provider Implementations (OpenAI, Anthropic, Gemini, Bedrock, Byteplus, OpenRouter)
  • Fallback Mechanisms & Retry Logic (see <fallback_mechanisms>)
  • Region Configuration for AWS Bedrock (see <region_configuration>)

Prompt Management:

  • Prompt Templating System with {{variables}} (see <prompt_templating>)
  • Prompt Design Patterns (YAML-structured, role-based) (see <prompt_design_patterns>)
  • Dynamic Variables & Function Mapping (see <dynamic_variables>)

External API Integration:

  • External API Managers (Astrology, Weather, etc.)
  • Data Transformation Pipelines (validate → normalize → enrich → format)
  • Multi-Layer Caching Strategy (instance → distributed → database)

Production Considerations:

  • JWT Authentication & Security (see <authentication_security>)
  • Caching Strategies (token cache, response cache)
  • Monitoring & Observability (Langfuse integration)
  • Error Handling & Graceful Degradation

Code Examples:

  • Complete Working Code Samples (see <implementation_examples>)

</domain_knowledge_index>

<database_schema>

Django Models for AI-Integrated Backend

Bot Model (Core Entity)
python
class Bot(models.Model):
uuid = models.UUIDField(default=uuid4, editable=False, unique=True)
user = models.ForeignKey("users.UserProfile", on_delete=models.CASCADE, related_name="bots")
# Identity
name = models.CharField(max_length=255)
slug = models.SlugField(max_length=255, unique=True, blank=True, db_index=True)
description = models.TextField(blank=True)
avatar = models.CharField(max_length=255, null=True, blank=True)
# Status and Type
status = models.CharField(max_length=20, choices=BotStatus.choices, default=BotStatus.DRAFT, db_index=True)
bot_type = models.CharField(max_length=30, choices=BotType.choices, default=BotType.COMPANION)
# Configuration
rank = models.PositiveIntegerField(default=0, db_index=True)
metadata = models.JSONField(default=dict, blank=True) # Store required_fields, pricing, etc.
# Timestamps
launched_on = models.DateTimeField(null=True, blank=True, db_index=True)
created_on = models.DateTimeField(auto_now_add=True)
updated_on = models.DateTimeField(auto_now=True)
deleted_at = models.DateTimeField(null=True, blank=True, db_index=True)

Key Design Decisions:

  • metadata JSONField for flexible per-bot configuration (required_fields, character_rating, pricing)
  • Soft deletion with deleted_at timestamp instead of hard delete
  • slug auto-generated from name for SEO-friendly URLs
  • rank for custom ordering in UI
BotLLMConfig Model (Multi-Provider Configuration)
python
class BotLLMConfig(models.Model):
bot = models.ForeignKey(Bot, on_delete=models.CASCADE, related_name="llm_configs")
# LLM Configuration
prompt = models.TextField(blank=True) # Can be template with {{variables}}
model_name = models.CharField(max_length=100) # e.g., "gpt-4", "claude-3-sonnet", "gemini-2.5-pro"
llm_provider = models.CharField(max_length=50, choices=BotLLMProvider.choices) # openai, anthropic, gemini, bedrock, etc.
# Generation Parameters
temperature = models.FloatField(default=0.7)
top_p = models.FloatField(default=0.95)
top_k = models.IntegerField(null=True, blank=True)
max_output_tokens = models.PositiveIntegerField(default=1024)
# Activation
is_active = models.BooleanField(default=False) # Only one active config per bot
# Additional Configuration
metadata = models.JSONField(default=dict, blank=True) # Store region_name, tools, etc.
created_on = models.DateTimeField(auto_now_add=True)
updated_on = models.DateTimeField(auto_now=True)
class Meta:
db_table = "llm_configurations"
ordering = ["-is_active", "created_on"]
def save(self, *args, **kwargs):
# Ensure only one active config per bot
if self.is_active:
BotLLMConfig.objects.filter(bot=self.bot, is_active=True).exclude(pk=self.pk).update(is_active=False)
super().save(*args, **kwargs)

Key Design Decisions:

  • One Bot can have multiple BotLLMConfig entries for A/B testing
  • is_active flag controls which config is used (only one active per bot)
  • Save method enforces single active config constraint
  • metadata stores provider-specific settings (e.g., region_name for AWS Bedrock)
BotLLMProvider Choices
python
class BotLLMProvider(models.TextChoices):
OpenAI = "openai", _("OpenAI")
GEMINI = "gemini", _("Gemini")
ANTHROPIC = "anthropic", _("Anthropic")
GROQ = "groq", _("Groq")
AI_SDK = "ai-sdk", _("AI-SDK")
BEDROCK = "bedrock", _("Bedrock")
BYTEPLUS = "byteplus", _("Byteplus")
OPENROUTER = "openrouter", _("OpenRouter")

Why This Design:

  • Supports multiple providers without code changes
  • Easy to add new providers (add to choices, implement integration)
  • Database-level validation ensures valid provider names

</database_schema>

<fallback_mechanisms>

Intelligent Fallback Routing

Core Fallback Pattern (from Production Code)
python
def get_fallback_routing(provider: str, model_name: str, system_instruction: str, llm_metadata: dict = None):
"""
Ensures system_instruction and region_name are added properly to fallback chain.
Args:
provider: Primary provider (gemini, bedrock, byteplus, etc.)
model_name: Model identifier (gemini-2.5-pro, deepseek.v3-v1:0, etc.)
system_instruction: System prompt to pass to all fallbacks
llm_metadata: Additional metadata including region_name for Bedrock
Returns:
List of fallback configurations, each containing:
- provider: str
- model: str
- retry: int (0 = no retry, >0 = retry count)
- system_instruction: str
- region_name: str (for Bedrock only)
"""
provider = (provider or "").lower()
fallbacks = []

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 95 of 100Pattern checks on the skill's files.
  • Model reviewPassed

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

Repository stars
6
7-day trend score
10

Stars and forks are for the whole GitHub repository, not this skill alone. Refreshed 24 Mar 2026, 7 months ago.

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/twofourlabs/agent-docs/ai-integrated-api-backend/badge)](https://verified-skill.com/skills/twofourlabs/agent-docs/ai-integrated-api-backend)

Something wrong with this skill or its page? Tell us.