Skip to main content

Shared AI-powered creative writing and tool-use services for BF Agent ecosystem

Project description

Creative Services

Shared AI-powered creative writing services for BF Agent, Travel Beat, and other platform apps.

Overview

This package provides modular, reusable creative AI services:

  • Prompt Template System - Type-safe prompt management with Pydantic schemas
  • LLM Client - Unified client for OpenAI, Anthropic, Groq, Ollama
  • LLM Registry - DB-driven LLM configuration (switch models without code changes)
  • Dynamic Client - Tier-based LLM selection (economy/standard/premium)
  • Usage Tracker - Token and cost tracking
  • Security - Prompt injection detection and input sanitization
  • Caching - Redis and in-memory caching with TTL
  • Observability - Prometheus metrics and structured events

Installation

# Basic installation
pip install -e ../platform/packages/creative-services

# With OpenAI support
pip install -e ../platform/packages/creative-services[openai]

# With all LLM providers
pip install -e ../platform/packages/creative-services[all]

Quick Start

Simple Usage (Environment Variables)

from creative_services import DictRegistry, DynamicLLMClient, LLMTier
import asyncio

# Create registry from environment variables
registry = DictRegistry.from_env()
client = DynamicLLMClient(registry)

# Generate with tier-based selection
async def main():
    response = await client.generate(
        prompt="Write a short story about a traveler",
        system_prompt="You are a creative writer",
        tier=LLMTier.STANDARD,  # Uses GPT-4o-mini or Claude Sonnet
    )
    print(response.content)

asyncio.run(main())

Django Integration (BFAgent/TravelBeat)

from creative_services.adapters import DjangoLLMRegistry, BFAgentLLMBridge
from apps.bfagent.models import Llms

# Option 1: Use Django-backed registry
registry = DjangoLLMRegistry(Llms)
client = DynamicLLMClient(registry)

# Option 2: Use compatibility bridge (no code changes needed)
bridge = BFAgentLLMBridge.with_django_registry(Llms)
result = bridge.generate_text("Hello", tier="premium")

Backward Compatibility (Drop-in Replacement)

# Replace existing BFAgent imports:
# from apps.bfagent.services.llm_client import generate_text

# With:
from creative_services.adapters import generate_text

# Same API, uses new infrastructure
result = generate_text("Hello", tier="standard")

Architecture

creative_services/
โ”œโ”€โ”€ prompts/                    # ๐Ÿ†• Prompt Template System
โ”‚   โ”œโ”€โ”€ schemas/                # Pydantic schemas (frozen, immutable)
โ”‚   โ”‚   โ”œโ”€โ”€ variables.py        # PromptVariable, VariableType
โ”‚   โ”‚   โ”œโ”€โ”€ llm_config.py       # LLMConfig, RetryConfig
โ”‚   โ”‚   โ”œโ”€โ”€ template.py         # PromptTemplateSpec
โ”‚   โ”‚   โ””โ”€โ”€ execution.py        # PromptExecution, ExecutionStatus
โ”‚   โ”œโ”€โ”€ security/               # Injection detection & sanitization
โ”‚   โ”œโ”€โ”€ registry/               # Template storage backends
โ”‚   โ”‚   โ”œโ”€โ”€ memory.py           # InMemoryRegistry
โ”‚   โ”‚   โ”œโ”€โ”€ file.py             # FileRegistry (YAML/JSON)
โ”‚   โ”‚   โ””โ”€โ”€ django_registry.py  # DjangoRegistry
โ”‚   โ”œโ”€โ”€ execution/              # Execution engine
โ”‚   โ”‚   โ”œโ”€โ”€ executor.py         # PromptExecutor
โ”‚   โ”‚   โ”œโ”€โ”€ renderer.py         # Jinja2 template rendering
โ”‚   โ”‚   โ”œโ”€โ”€ cache.py            # InMemoryCache
โ”‚   โ”‚   โ”œโ”€โ”€ redis_cache.py      # RedisCache
โ”‚   โ”‚   โ””โ”€โ”€ retry.py            # Retry with backoff
โ”‚   โ”œโ”€โ”€ observability/          # Metrics & events
โ”‚   โ”œโ”€โ”€ migration/              # BFAgent compatibility
โ”‚   โ””โ”€โ”€ integration/            # Ready-to-use clients
โ”‚       โ”œโ”€โ”€ bfagent.py          # BFAgent integration
โ”‚       โ””โ”€โ”€ llm_clients.py      # OpenAI, Anthropic clients
โ”œโ”€โ”€ core/                       # Core LLM infrastructure
โ”œโ”€โ”€ adapters/                   # Django adapters
โ”œโ”€โ”€ character/                  # Character generation
โ”œโ”€โ”€ world/                      # World building
โ””โ”€โ”€ story/                      # Story generation

LLM Tiers

Tier Models Use Case
ECONOMY GPT-3.5, Claude Haiku, Groq Llama Simple tasks, high volume
STANDARD GPT-4o-mini, Claude Sonnet Balanced quality/cost
PREMIUM GPT-4o, Claude Opus Complex tasks, best quality
LOCAL Ollama (Llama, Mistral) Offline, privacy-sensitive

Supported LLM Providers

  • OpenAI (GPT-4o, GPT-4o-mini, GPT-3.5)
  • Anthropic (Claude 3.5 Sonnet, Claude 3 Opus, Claude 3 Haiku)
  • Groq (Llama 3.3 70B - fast & free)
  • Ollama (Local models)

Migration Guide

For BFAgent

  1. Install creative-services: pip install -e ../platform/packages/creative-services
  2. Existing code continues to work (no changes needed)
  3. New code can use DynamicLLMClient directly
  4. Gradually migrate old code to new API

For TravelBeat

  1. Install creative-services
  2. Replace direct OpenAI calls with DynamicLLMClient
  3. Use LLMTier.STANDARD for story generation

Prompt Template System (New!)

Type-safe prompt management with 195 tests:

from creative_services.prompts import (
    PromptTemplateSpec,
    PromptVariable,
    PromptExecutor,
    InMemoryRegistry,
)
from creative_services.prompts.integration import OpenAIClient

# Define template
template = PromptTemplateSpec(
    template_key="greeting.v1",
    domain_code="examples",
    name="Greeting",
    system_prompt="You are friendly.",
    user_prompt="Say hello to {{ name }}!",
    variables=[PromptVariable(name="name", required=True)],
)

# Save and execute
registry = InMemoryRegistry()
registry.save(template)

executor = PromptExecutor(
    registry=registry,
    llm_client=OpenAIClient(),
    app_name="my_app",
)

result = await executor.execute(
    template_key="greeting.v1",
    variables={"name": "Alice"},
)
print(result.content)

BFAgent Integration

from creative_services.prompts.integration import create_bfagent_executor

executor = create_bfagent_executor()
result = await executor.execute(
    template_key="character.backstory.v1",
    variables={"name": "Elara", "genre": "fantasy"},
)

Documentation

Full documentation available at docs/:

cd docs && make html
# Open _build/html/index.html

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

iil_creative_services-0.3.0.tar.gz (101.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

iil_creative_services-0.3.0-py3-none-any.whl (98.9 kB view details)

Uploaded Python 3

File details

Details for the file iil_creative_services-0.3.0.tar.gz.

File metadata

  • Download URL: iil_creative_services-0.3.0.tar.gz
  • Upload date:
  • Size: 101.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.10.12

File hashes

Hashes for iil_creative_services-0.3.0.tar.gz
Algorithm Hash digest
SHA256 8dfa75c1f5541aed9e31f57f364558f4d3a5c2ac4d47e0dcaabb4d3c10ce4d36
MD5 382d58aa1a6df9219900324e32d09228
BLAKE2b-256 369de170b785e331440e8d1456bbc73750c56086b1e74a9f29b0431cd46d5be7

See more details on using hashes here.

File details

Details for the file iil_creative_services-0.3.0-py3-none-any.whl.

File metadata

File hashes

Hashes for iil_creative_services-0.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 ee43fe920a05bb21264768901a89f1a4bb5aeecabf01b576c8b731be85a604a5
MD5 ee1d1332b1f64d49d6dd999a3fc4bcc1
BLAKE2b-256 fb315c5b3e32996fa0b265ec44f87a1980bebbf1c38ac9272f3f702469afe890

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page