Skip to main content

The Stateless Unified Single-Markdown Multi-Tenant Ticket Prioritizer & Router Library

Project description

ticket-controller

The Stateless, Framework-Agnostic Single-Markdown Multi-Tenant Ticket Prioritizer & Router

ticket-controller is an enterprise-grade, high-performance, and entirely stateless Python library built to ingest complex, unstructured, or heavy multi-tenant JSON ticket payloads, automatically isolate text strings, and run contextual priority classification and webhook routing.

Unlike heavy AI orchestration frameworks, ticket-controller cuts out middleware lag by communicating directly with native LLM APIs (like local Ollama or cloud-hosted Google Gemini, OpenAI and ANthropic). It features an incredibly small installation footprint, ultra-fast direct execution, and dynamic lazy-loading dependencies.

This document serves as the official operational manual for both GitHub and PyPI integration. It is strictly formatted to guide both Human Engineers and automated AI Coding Agents building production pipelines.


Core Operational Lifecycle

When you pass a raw dictionary payload into the engine, four core sub-features execute silently in sequence inside a single unified loop to eliminate processing overhead.

INCOMING COMPLEX TICKET DICTIONARY VALVE Ingests raw payload with video, photos, system log arrays, or binary metadata links an sends it to the following sub-features:

1. SCHEMA PRE-VALIDATION & DIRECTORY IDENTIFICATION Detects blueprint configuration signatures or uses explicit ticket profiles locally.

2. HIGH-SPEED LOCAL PII PROTECTION MASKING Scrubs emails and phone numbers via fast regex before data leaves your local machine.

3. UNIFIED SINGLE-PASS NATIVE LLM INFERENCE Bypasses heavy framework lag; executes extraction, triage, and routing a single pass.

4. WEBHOOK ENRICHMENT MAPPING & PII RECOVERY Resolves calculated destination to automation URLs; restores real private strings locally.

OUTGOING STRONGLY TYPED RETURN OBJECT VARIABLE Hands a validated Pydantic data package directly back to your running thread.


Key Architectural Superpowers

1. Infinite Data Volume & Ticket Size Scaling (-Text_Content_Fields)

The library is designed with an abstract core. The text extraction engine accepts a list of layout content keys. This allows the system to crawl, extract, and combine multiple massive data fields from complex tickets concurrently without crashing your data structures.

  • Example:
    - Text_Content_Fields: ["user_complaint", "error_log_dump", "stack_trace_text", "env_variables"]
    

Whether a ticket is a 5-word message or a 10,000-word system log block, the engine extracts the core data, masks PII locally, and feeds only the cleaned context straight to the model.

2. Deep Conditional Logic & Keyword Override Traps (##RULES)

Because business rules live entirely inside clean Markdown files, developers can implement multi-layered conditional logic matrices. The engine uses advanced reasoning to look past simple word matching. It easily navigates complex keyword override traps:

  • Example: A medical ticket mentioning "severe pain" can trigger an override rule that automatically downgrades the priority to MEDIUM if it explicitly confirms "No head trauma".

3. Stateless Multi-Turn Lifecycle Awareness (-Updates_Timeline_Field)

By setting an optional timeline history tracker anchor, the library gains full temporal awareness across a ticket's entire lifespan. As a ticket moves between teams and gains new unformatted comments, the library re-evaluates the historical timeline on every turn, allowing the LLM to dynamically update priorities and webhook destinations on-the-fly.

4. Production Token Footprint Optimization (enable_trace)

Generating a line-by-line justification text block for thousands of tickets an hour causes significant token bloat and slows down system speeds. ticket-controller fixes this with a built-in enable_trace flag:

  • enable_trace=True (Testing Mode): Generates deep audit traces explaining exactly why rules matched.
  • enable_trace=False (Production Mode): Injects strict structural instructions forcing the model to skip trace generation entirely. This reduces your output token footprint to the absolute bare minimum, maximizing processing speeds.

Required Markdown Configuration Structuring

To use the engine, create a dedicated blueprints folder (e.g., ./my_blueprints). You must build one single Markdown file per ticket type (e.g., patient_triage.md, staff_maintenance.md).

The MANDATORY Golden Rule for Blueprints: Your JSON payload keys can be completely custom, but your left-hand Markdown layout text anchors (- ID_Field:, - Text_Content_Fields:, - Updates_Timeline_Field:) must use these exact case-sensitive spellings.

TICKET LAYOUT MARKDOWN BLUEPRINT:

# CHOSEN WORKFLOW PROFILE BLUEPRINT HEADER

## Layout
- ID_Field: "exact_json_key_holding_the_ticket_id"
- Text_Content_Fields:  ["list_of", "json_keys", "to_extract", "from" ] 
- Updates_Timeline_Field: "optional_json_key_holding_history_notes_list_arrays"

## Priorities
- TIER_NAME_1: Detailed description of what this operational priority means.
- TIER_NAME_2: Detailed description of what this operational priority means.

## Destinations
- EXACT_UPPERCASE_TEAM_NAME_1 -> https://company.com
- EXACT_UPPERCASE_TEAM_NAME_2 -> https://company.com

## Rules
1. General baseline routing rules mapping keywords to targets.
2. OVERRIDE RULE: Highly specific conditional instructions taking logical precedence over general rules.

Project Installation & Switchboard Setup

1. Library Installation

Developers minimize download bloat by fetching only the package dependencies required for their targeted runtime provider using python extras:

# To run locally using pure python requests and Ollama models
pip install ticket-controller[ollama]

# To run in the cloud using Google Gemini models
pip install ticket-controller[google]

# To run in the cloud using OpenAI models
pip install ticket-controller[openai]

# To run in the cloud using Anthropic models
pip install ticket-controller[anthropic]

# Or install all dependencies for flexibility
pip install ticket-controller[all]

2. Configure Your .env Environment Wallet

Create an environment file named .env at the root of your application to route your model backend switcher:

# PROVIDER CHOICES: "ollama", "google", "openai"
AI_PROVIDER="google"
AI_MODEL_NAME="gemini-2.5-flash"

# Cloud Secret Provider Tokens (Leave blank for local Ollama runtimes)
GEMINI_API_KEY="your_real_gemini_api_key_here"
OPENAI_API_KEY="your_real_openai_api_key_here"
ANTHROPIC_API_KEY="your_real_anthropic_api_key_here"

Code Integration Patterns

1. Unified Programmatic Triage Loop (With Production Token Optimization)

This example demonstrates importing the core client directly, passing a massive multi-tenant ticket payload with attachment matrices, running auto-detection, and turning off trace generation to save tokens.

import os
from ticket-controller.core import TicketController

# 1. Initialize the direct code-level router client instance once at boot time
# This dynamically indexes every .md file inside your blueprints directory
router = TicketController(
    config_dir="./my_blueprints",
    provider=os.environ.get("AI_PROVIDER", "google"),
    model_name=os.environ.get("AI_MODEL_NAME", "gemini-2.5-flash")
)

# 2. Setup your raw, heavy production data object packet containing attachments and PII
raw_incoming_ticket_payload = {
    "ticket_id": "ER-20240718-002",
    "patient_id": "P-123456789",
    "patient_name": "Alexander Sterling", # Masked locally before cloud transfer
    "patient_email": "alex.sterling@hospital.com", # Redacted completely via regex
    "chief_complaint": "Fall, possible ankle fracture",
    "emergency_notes": "72 y/o female fell at home. Complains of severe pain in right ankle. No head trauma or loss of consciousness. HX of osteoporosis.",
    "attachments": [
        {"file_name": "Ankle_Xray_Order.pdf", "size_kb": 180, "url": "https://storage/scans/ankle.pdf"},
        {"file_name": "Injury_Photo.jpg", "size_kb": 800, "url": "https://storage/images/ankle.jpg"}
    ]
}

# 3. Process the ticket through the single-pass core loop
# - Setting 'ticket_type = None' activates Auto-Detect mode to match signature keys on-the-fly! If you have mimited types of tickets, specify the ticket type to reduce additional llm token calls. 
# - Setting 'enable_trace=False' activates high-volume production mode, dropping output tokens to a minimum! By default enable_trace is set to False. You can set it to True to let LLM provide details on reasoning.

result = router.prioritize(
    raw_ticket_payload=raw_incoming_ticket_payload, 
    ticket_type=None, 
    enable_trace=False
)

# 4. Use the strongly typed return attributes immediately in your app's routing channels
print(result.ticket_no)                 # Output: "ER-20240718-002"
print(result.assigned_priority)         # Output: "MEDIUM" (Complex Override Rules Matched!)
print(result.next_routing_destination)  # Output: "RADIOLOGY_LAB_XRAY"
print(result.target_webhook)            # Output: "https://hospital.local"
print(result.detected_blueprint)        # Output: "patient_triage.md"
print(result.inference_duration)        # Output: 0.3842 (Float seconds metrics tracking)

# Original payload and sensitive PII keys are returned safely intact and restored!
print(result.original_payload["patient_name"]) # Output: "Alexander Sterling"

# Optional Tool: Save this transaction's analytics metrics to a local CSV sheet row
result.log_to_audit_trail()

2. Multi-Turn Ongoing Ticket Updates Loop

To process an ongoing ticket on its 2nd or 3rd turn, include your chronological history list array directly inside your custom JSON dictionary payload. The engine evaluates the full history timeline against your rules seamlessly:

turn_2_updated_ticket = {
    "ticket_id": "ER-20240718-002",
    "chief_complaint": "Fall, possible ankle fracture",
    "emergency_notes": "72 y/o female fell at home. Complains of severe pain in right ankle.",
    
    # CHRONOLOGICAL TIMELINE LEDGER ARRAY MATCHING YOUR BLUEPRINT LAYOUT DEFINITIONS:
    "doctor_handoff_notes_list": [
        {
            "timestamp": 17181045,
            "author": "Dr. John Smith",
            "note": "Initial examination complete. Extreme localized right ankle tenderness. History of osteoporosis. Scheduling immediate diagnostic ultrasound scans to verify bone degradation."
        }
    ]
}

# Fire using explicit routing to maximize execution speed (Bypasses auto-detection pass)
result_turn_2 = router.prioritize(
    raw_ticket_payload=turn_2_updated_ticket,
    ticket_type="patient_triage",
    enable_trace=True # Enabled for debugging verification
)

print(result_turn_2.next_routing_destination) # Output: Shifts automatically based on timeline updates!

Errors, Exceptions & Troubleshooting

ticket-controller implements descriptive, custom Python exceptions to make integration diagnostics straightforward and prevent silent application server crashes:

1. TicketLayoutValidationError

  • Why it happens: The incoming JSON keys do not contain the target properties matching your single markdown layout rules. This also triggers in auto-detect mode if a packet matches multiple or zero blueprints.
  • The Fix: Verify your incoming payload key strings, or modify the - ID_Field: and - Text_Content_Fields: values inside your blueprint file to align with your dataset.

2. ImportError

  • Why it happens: You initialized a specific cloud provider framework backend in your initialization code or system environment configurations (e.g., provider="google"), but forgot to fetch its required package dependencies during installation.
  • The Fix: Run the appropriate installation command to fetch the missing vendor extras: pip install ticket-controller[google]

3. RuntimeError

  • Why it happens: The network connectivity pipeline dropped or timed out mid-inference. This usually occurs if a local Ollama background process daemon freezes, turns off, or runs out of system memory capacity.
  • The Fix: Ensure your local Ollama engine is running in the background, or check your API keys and internet connection if using cloud platforms.

Project details


Download files

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

Source Distributions

No source distribution files available for this release.See tutorial on generating distribution archives.

Built Distribution

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

ticket_controller-1.0.0-py3-none-any.whl (13.6 kB view details)

Uploaded Python 3

File details

Details for the file ticket_controller-1.0.0-py3-none-any.whl.

File metadata

File hashes

Hashes for ticket_controller-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 8f3895d543a10f17c7977be071119391c7fcf6f80704af67b170023f21098b06
MD5 7103f26a967883d0abe4209b94b1740a
BLAKE2b-256 39c1c70b51cf0a82059a28d966f824994f772dbf39701e08ec974e97544097f7

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