Lightspeed Core Stack (LCS) is an AI-powered assistant built on FastAPI that provides answers using LLM services, agents, and RAG databases. It integrates with Llama Stack for AI operations.
- Python: Check
pyproject.tomlfor supported Python versions - Package Manager: uv (use
uv runfor all commands) - Required Commands:
uv run make format- Format code (black + ruff)uv run make verify- Run all linters (black, pylint, pyright, ruff, docstyle, check-types)
src/
βββ app/ # FastAPI application
βΒ Β βββ endpoints/ # REST API endpoints
βΒ Β βΒ Β βββ a2a_openapi.py # OpenAPI-only metadata for A2A JSON-RPC routes
βΒ Β βΒ Β βββ a2a.py # Handler for A2A (Agent-to-Agent) protocol endpoints using Responses API
βΒ Β βΒ Β βββ authorized.py # Handler for REST API call to authorized endpoint
βΒ Β βΒ Β βββ config.py # Handler for REST API call to retrieve service configuration
βΒ Β βΒ Β βββ conversations_v1.py # Handler for REST API calls to manage conversation history using Conversations API
βΒ Β βΒ Β βββ conversations_v2.py # Handler for REST API calls to manage conversation history
βΒ Β βΒ Β βββ feedback.py # Handler for REST API endpoint for user feedback
βΒ Β βΒ Β βββ health.py # Handlers for health REST API endpoints
βΒ Β βΒ Β βββ info.py # Handler for REST API call to provide info
βΒ Β βΒ Β βββ mcp_auth.py # Handler for REST API calls related to MCP server authentication
βΒ Β βΒ Β βββ mcp_servers.py # Handler for REST API calls to dynamically manage MCP servers
βΒ Β βΒ Β βββ metrics.py # Handler for REST API call to provide metrics
βΒ Β βΒ Β βββ models.py # Handler for REST API call to list available models
βΒ Β βΒ Β βββ prompts.py # Handler for REST API calls to manage Llama Stack stored prompt templates
βΒ Β βΒ Β βββ providers.py # Handler for REST API calls to list and retrieve available providers
βΒ Β βΒ Β βββ query.py # Handler for REST API call to provide answer to query using Response API
βΒ Β βΒ Β βββ rags.py # Handler for REST API calls to list and retrieve available RAGs
βΒ Β βΒ Β βββ responses.py # Handler for REST API call to provide answer using Responses API (LCORE specification)
βΒ Β βΒ Β βββ responses_telemetry.py # Splunk telemetry helpers for the Responses API endpoint
βΒ Β βΒ Β βββ rlsapi_v1.py # Handler for RHEL Lightspeed rlsapi v1 REST API endpoints
βΒ Β βΒ Β βββ root.py # Handler for the / endpoint
βΒ Β βΒ Β βββ saved_prompts.py # Handler for REST API calls to manage saved prompts
βΒ Β βΒ Β βββ shields.py # Handler for REST API call to list available shields
βΒ Β βΒ Β βββ streaming_query.py # Streaming query handler using Responses API
βΒ Β βΒ Β βββ stream_interrupt.py # Endpoint for interrupting in-progress streaming query requests
βΒ Β βΒ Β βββ tools.py # Handler for REST API call to list available tools from MCP servers
βΒ Β βΒ Β βββ vector_stores.py # Handler for REST API calls to manage vector stores and files
βΒ Β βββ database.py # Database engine management
βΒ Β βββ routers.py # All REST API routers
βΒ Β βββ main.py # Application entry point
βββ a2a_storage/ # A2A protocol persistent storage
βΒ Β βββ context_store.py # Abstract base class for context stores
βΒ Β βββ in_memory_context_store.py # In-memory implementation
βΒ Β βββ sqlite_context_store.py # SQLite implementation
βΒ Β βββ postgres_context_store.py # PostgreSQL implementation
βΒ Β βββ storage_factory.py # Factory for creating stores
βββ authentication/ # Authentication modules (k8s, jwk, noop, rh-identity)
βΒ Β βββ api_key_token.py # Authentication flow for FastAPI endpoints with a provided API key
βΒ Β βββ interface.py # Abstract base class for all authentication method implementations
βΒ Β βββ jwk_token.py # Manage authentication flow for FastAPI endpoints with JWK based JWT auth
βΒ Β βββ k8s.py # Manage authentication flow for FastAPI endpoints with K8S/OCP
βΒ Β βββ noop.py # Manage authentication flow for FastAPI endpoints with no-op auth
βΒ Β βββ noop_with_token.py # Manage authentication flow for FastAPI endpoints with no-op auth and provided user token
βΒ Β βββ rh_identity.py # Red Hat Identity header authentication for FastAPI endpoints
βΒ Β βββ trusted_proxy.py # Trusted-proxy authentication module for requests forwarded by a K8s proxy
βΒ Β βββ utils.py # Authentication utility functions
βββ authorization/ # Authorization middleware & resolvers
βΒ Β βββ azure_token_manager.py # Azure Entra ID token manager for Azure OpenAI authentication
βΒ Β βββ middleware.py # Authorization middleware and decorators
βΒ Β βββ resolvers.py # Authorization resolvers for role evaluation and access control
βββ cache/ # Conversation cache implementations
βΒ Β βββ cache.py # Abstract class that is parent for all cache implementations
βΒ Β βββ cache_entry.py # Model for conversation history cache entry
βΒ Β βββ cache_error.py # Any exception that can occur during cache operations
βΒ Β βββ cache_factory.py # Cache factory class
βΒ Β βββ in_memory_cache.py # In-memory cache implementation
βΒ Β βββ noop_cache.py # No-operation cache implementation
βΒ Β βββ postgres_cache.py # PostgreSQL cache implementation
βΒ Β βββ sqlite_cache.py # Cache that uses SQLite to store cached values
βββ data/ # Built-in default Llama Stack baseline for unified-mode synthesis
βΒ Β βββ default_run.yaml # The starting point when a unified `lightspeed-stack.yaml` select default baseline
βββ quota/ # Quota limiter and token usage tracking
βΒ Β βββ cluster_quota_limiter.py # Simple cluster quota limiter where quota is fixed for the whole cluster
βΒ Β βββ connect_pg.py # PostgreSQL connection handler
βΒ Β βββ connect_sqlite.py # SQLite connection handler
βΒ Β βββ quota_exceed_error.py # Any exception that can occur when a user does not have enough tokens available
βΒ Β βββ quota_limiter.py # Abstract class that is the parent for all quota limiter implementations
βΒ Β βββ quota_limiter_factory.py # Quota limiter factory class
βΒ Β βββ revokable_quota_limiter.py # Simple quota limiter where quota can be revoked
βΒ Β βββ sql.py # SQL commands used by quota management package
βΒ Β βββ token_usage_history.py # Class with implementation of storage for token usage history
βΒ Β βββ user_quota_limiter.py # Simple user quota limiter where each user has a fixed quota
βββ metrics/ # Prometheus metrics
βΒ Β βββ __init__.py # Metrics module for Lightspeed Core Stack
βΒ Β βββ recording.p # Recording helpers for Prometheus metricsy
βΒ Β βββ utils.py # Utility functions for metrics handling
βββ runners/ # Runners for various LCore subsystems
βΒ Β βββ quota_scheduler.py # User and cluster quota scheduler runner
βΒ Β βββ uvicorn.py # Uvicorn runner
βββ models/ # Pydantic models
βΒ Β βββ api/ # REST API models
βΒ Β βΒ Β βββ requests/ # REST API request models
βΒ Β βΒ Β βΒ Β βββ __init__.py # Concrete REST API request models grouped by domain
βΒ Β βΒ Β βΒ Β βββ catalog.py # Request models for catalog-related endpoints
βΒ Β βΒ Β βΒ Β βββ conversations.py # Request models for conversation endpoints
βΒ Β βΒ Β βΒ Β βββ feedback.py # Request models for feedback endpoints
βΒ Β βΒ Β βΒ Β βββ mcp_servers.py # Request models for MCP server registration
βΒ Β βΒ Β βΒ Β βββ prompts.py # Request models for prompt template endpoints
βΒ Β βΒ Β βΒ Β βββ query.py # Request models for query and streaming interrupt endpoints
βΒ Β βΒ Β βΒ Β βββ responses_openai.py # Request model for the OpenAI-compatible Responses API
βΒ Β βΒ Β βΒ Β βββ rlsapi.py # Models for rlsapi v1 REST API requests
βΒ Β βΒ Β βΒ Β βββ vector_stores.py # Request models for vector store and file endpoints
βΒ Β βΒ Β βββ responses/ # HTTP response models
βΒ Β βΒ Β βββ constants.py # OpenAPI description strings and shared example-label lists for API responses
βΒ Β βΒ Β βββ error/ # Error responses
βΒ Β βΒ Β βΒ Β βββ bad_request.py # OpenAPI-aligned error response models: HTTP 400 Bad Request
βΒ Β βΒ Β βΒ Β βββ bases.py # Base Pydantic types for OpenAPI-aligned structured API error responses
βΒ Β βΒ Β βΒ Β βββ conflict.py # OpenAPI-aligned error response models: HTTP 409 Conflict
βΒ Β βΒ Β βΒ Β βββ content_too_large.py # OpenAPI-aligned error response models: HTTP 413 Payload Too Large
βΒ Β βΒ Β βΒ Β βββ forbidden.py # OpenAPI-aligned error response models: HTTP 403 Forbidden
βΒ Β βΒ Β βΒ Β βββ internal.py # OpenAPI-aligned error response models: HTTP 500 Internal Server Error
βΒ Β βΒ Β βΒ Β βββ not_found.py # OpenAPI-aligned error response models: HTTP 404 Not Found
βΒ Β βΒ Β βΒ Β βββ service_unavailable.py # OpenAPI-aligned error response models: HTTP 503 Service Unavailable
βΒ Β βΒ Β βΒ Β βββ too_many_requests.py # OpenAPI-aligned error response models: HTTP 429 Too Many Requests
βΒ Β βΒ Β βΒ Β βββ unauthorized.py # OpenAPI-aligned error response models: HTTP 401 Unauthorized
βΒ Β βΒ Β βΒ Β βββ unprocessable_entity.py # OpenAPI-aligned error response models: HTTP 422 Unprocessable Entity
βΒ Β βΒ Β βββ successful/ # Successful responses
βΒ Β βΒ Β βββ bases.py # Base classes for successful API response models
βΒ Β βΒ Β βββ catalog.py # Successful response bodies for catalog-style endpoints
βΒ Β βΒ Β βββ configuration.py # Successful response model for the configuration endpoint
βΒ Β βΒ Β βββ conversations.py # Successful responses for conversation CRUD and listing
βΒ Β βΒ Β βββ feedback.py # Successful responses for feedback and feedback status endpoints
βΒ Β βΒ Β βββ mcp_servers.py # Successful responses for MCP server registration and listing
βΒ Β βΒ Β βββ probes.py # Successful probe-related API responses (info, readiness, liveness, status, auth)
βΒ Β βΒ Β βββ prompts.py # Successful responses for stored prompt templates
βΒ Β βΒ Β βββ query.py # Successful response models for synchronous query and streaming query documentation
βΒ Β βΒ Β βββ responses_openai.py # Successful response model for the OpenAI-compatible Responses API
βΒ Β βΒ Β βββ rlsapi.py # Models for rlsapi v1 REST API responses
βΒ Β βΒ Β βββ saved_prompts.py # Successful responses for saved prompts configuration
βΒ Β βΒ Β βββ vector_stores.py # Successful responses for vector stores and vector store files
βΒ Β βββ common/ # Shared cross-layer models
βΒ Β βΒ Β βββ agents/ # Streaming payload models and event type exports
βΒ Β βΒ Β βΒ Β βββ stream_payloads.py # Typed JSON bodies for SSE streaming events
βΒ Β βΒ Β βΒ Β βββ turn_accumulator.py # Mutable per-turn state for agent response processing
βΒ Β βΒ Β βββ responses/ # Shared models for the OpenAI-compatible Responses API pipeline
βΒ Β βΒ Β βΒ Β βββ contexts.py # Context objects for the responses endpoint pipeline and streaming query generators.
βΒ Β βΒ Β βΒ Β βββ responses_api_params.py # Request parameter model for Llama Stack responses API calls
βΒ Β βΒ Β βΒ Β βββ responses_conversation_context.py # Conversation resolution result model for the OpenAI-compatible responses endpoint
βΒ Β βΒ Β βΒ Β βββ types.py # Type aliases for OpenAI-compatible Responses API input shapes
βΒ Β βΒ Β βββ conversation.py # Conversation list rows, metadata, and simplified turn/message shapes for APIs
βΒ Β βΒ Β βββ feedback.py # Predefined feedback categories for AI response quality signals
βΒ Β βΒ Β βββ health.py # Health-related shared models for readiness and diagnostics
βΒ Β βΒ Β βββ mcp.py # MCP server metadata models shared by registration and list responses
βΒ Β βΒ Β βββ moderation.py # Shield moderation outcomes for the responses pipeline
βΒ Β βΒ Β βββ query.py # Shared query-related request primitives
βΒ Β βΒ Β βββ transcripts.py # Pydantic models for persisted query/response transcript entries
βΒ Β βΒ Β βββ turn_summary.py # RAG context, chunks, document refs, tool summaries, and per-turn aggregation
βΒ Β βββ compaction.py # Pydantic models for conversation compaction
βΒ Β βββ config.py # Model with service configuration
βΒ Β βββ database/ # Database models
βΒ Β βΒ Β βββ base.py # Base model for SQLAlchemy ORM classes
βΒ Β βΒ Β βββ conversations.py # User conversation models
βΒ Β βΒ Β βββ saved_prompts.py # User saved prompt models
βΒ Β βββ __init__.py # Database models package
βββ observability/ # Observability module for telemetry and event collection
βΒ Β βββ formats/ # Event format builders for Splunk telemetry
βΒ Β βΒ Β βββ responses.py # Event builders for Responses API Splunk format
βΒ Β βΒ Β βββ rlsapi.py # Event builders for rlsapi v1 Splunk format
βΒ Β βββ splunk.py # Async Splunk HEC client for sending telemetry events
βββ pydantic_ai_lightspeed/ # Pydantic AI integrations/extensions for Lightspeed Core Stack
βΒ Β βββ capabilities/ # Pluggable capabilities for pydantic-ai agents in Lightspeed
βΒ Β βΒ Β βββ question_validity/ # Question validity capability for agent input validation
βΒ Β βΒ Β βΒ Β βββ _capability.py # Question validity capability for filtering off-topic user queries
βΒ Β βΒ Β βββ redaction/ # PII redaction capability for Pydantic AI agents
βΒ Β βΒ Β βββ capability.py # Pydantic AI capability for PII redaction of model messages
βΒ Β βΒ Β βββ core.py # Core redaction logic for PII detection and replacement
βΒ Β βββ llamastack/ # Pydantic AI provider for Llama Stack
βΒ Β βββ _model.py # Custom OpenAI Responses model that works around Llama Stack streaming quirks
βΒ Β βββ _provider.py # Llama Stack provider implementation for Pydantic AI
βΒ Β βββ _transport.py # httpx transport that routes OpenAI-compatible requests through a Llama Stack library client
βββ telemetry/ # Telemetry module for configuration snapshot collection
βΒ Β βββ configuration_snapshot.py # Configuration snapshot with PII masking for telemetry
βββ utils/ # Utility functions
βΒ Β βββ agents/ # Agent streaming and non streaming helpers
βΒ Β βΒ Β βββ query.py # Non-streaming agent helpers and shared turn-summary builders for agent runs
βΒ Β βΒ Β βββ streaming.py # Agent streaming helpers for the streaming_query flow
βΒ Β βΒ Β βββ tool_processor.py # Process and record pydantic-ai tool parts during agent stream dispatch
βΒ Β βββ checks.py # Checks that are performed to configuration options
βΒ Β βββ common.py # Common utilities for the project
βΒ Β βββ compaction.py # Conversation compaction β partitioning, summarization, additive fold-up
βΒ Β βββ config_dumper.py # Function to dump the configuration schema into OpenAPI-compatible format
βΒ Β βββ connection_decorator.py # Decorator that makes sure the object is 'connected' according to it's connected predicate
βΒ Β βββ conversation_compaction.py # Runtime integration of conversation compaction into the request flow
βΒ Β βββ conversations.py # Utilities for conversations
βΒ Β βββ degraded_mode.py # Degraded mode state tracking
βΒ Β βββ endpoints.py # Utility functions for endpoint handlers
βΒ Β βββ json_schema_updater.py # Function to transform a JSON Schema-like dictionary into an OpenAPI-compatible schema
βΒ Β βββ llama_stack_version.py # Check if the Llama Stack version is supported by the LCS
βΒ Β βββ markdown_repair.py # Utilities for repairing truncated markdown content
βΒ Β βββ mcp_auth_headers.py # Utilities for resolving MCP server authorization headers
βΒ Β βββ mcp_headers.py # MCP headers handling
βΒ Β βββ mcp_oauth_probe.py # Probe MCP servers for OAuth and raise 401 with WWW-Authenticate when required
βΒ Β βββ models_dumper.py # Function to dump the schema of all data models into OpenAPI-compatible format
βΒ Β βββ openapi_schema_dumper.py # Utility function to dump schema with list of models into OpenAPI-compatible JSON format
βΒ Β βββ prompts.py # Utility functions for system prompts
βΒ Β βββ pydantic_ai_helpers.py # Helpers for running Pydantic AI agents against Llama Stack (Responses API compatibility)
βΒ Β βββ query.py # Utility functions for working with queries
βΒ Β βββ quota_utils.py # Quota handling helper functions
βΒ Β βββ reranker.py # Reranker utilities for RAG chunk reranking
βΒ Β βββ responses.py # Utility functions for processing Responses API output
βΒ Β βββ rh_identity.py # Utility functions for extracting RH Identity context for telemetry
βΒ Β βββ shields.py # Utility functions for working with Llama Stack shields
βΒ Β βββ streaming_sse.py # SSE formatting helpers for streaming query responses
βΒ Β βββ stream_interrupts.py # Stream interrupt registry and persistence utilities
βΒ Β βββ suid.py # Session ID utility functions
βΒ Β βββ token_counter.py # Helper classes to count tokens sent and received by the LLM
βΒ Β βββ token_estimator.py # Pre-LLM-call token estimation
βΒ Β βββ tool_formatter.py # Utility functions for formatting and parsing MCP tool descriptions
βΒ Β βββ transcripts.py # Transcript handling
βΒ Β βββ types.py # Common types for the project
βΒ Β βββ vector_search.py # Vector search utilities for query endpoints
βββ sentry.py # Sentry error tracking initialization and configuration
βββ lightspeed_stack.py # Entry point to the Lightspeed Core Stack REST API service
βββ llama_stack_configuration.py # Llama Stack configuration enrichment and synthesis
βββ log.py # Log utilities
βββ client.py # Llama Stack client wrapper (Singleton)
βββ configuration.py # Config management (Singleton)
βββ constants.py # Shared (final) constants
βββ version.py # Service version that is read by project manager tools
- Use absolute imports for internal modules:
from authentication import get_auth_dependency - FastAPI dependencies:
from fastapi import APIRouter, HTTPException, Request, status, Depends - Llama Stack imports:
from llama_stack_client import AsyncLlamaStackClient - ALWAYS check
pyproject.tomlfor existing dependencies before adding new ones - ALWAYS verify current library versions in
pyproject.tomlrather than assuming versions - Check
constants.pyfor shared constants before defining new ones
- All modules start with descriptive docstrings explaining purpose
- Use
logger = get_logger(__name__)fromlog.pyfor module logging - Package
__init__.pyfiles contain brief package descriptions - Central
constants.pyfor shared constants with descriptive comments - Type aliases defined at module level for clarity
- Use Final[type] as type hint for all constants
- All config uses Pydantic models extending
ConfigurationBase - Base class sets
extra="forbid"to reject unknown fields - Use
@field_validatorand@model_validatorfor custom validation - Type hints:
Optional[FilePath],PositiveInt,SecretStr
- Documentation: All functions require docstrings with brief descriptions
- Type Annotations: Complete type annotations for parameters and return types
- Use
typing_extensions.Selffor model validators - Union types:
str | int(modern syntax) - Optional:
Optional[Type]
- Use
- Naming: Use snake_case with descriptive, action-oriented names (get_, validate_, check_)
- Return Values: CRITICAL - Avoid in-place parameter modification anti-patterns:
# β BAD: Modifying parameter in-place def process_data(input_data: Any, result_dict: dict) -> None: result_dict[key] = value # Anti-pattern # β GOOD: Return new data structure def process_data(input_data: Any) -> dict: result_dict = {} result_dict[key] = value return result_dict
- Async Functions: Use
async deffor I/O operations and external API calls - Error Handling:
- Use FastAPI
HTTPExceptionwith appropriate status codes for API endpoints - Handle
APIConnectionErrorfrom Llama Stack
- Use FastAPI
- Use
from log import get_loggerand module logger pattern:logger = get_logger(__name__) - Standard log levels with clear purposes:
logger.debug()- Detailed diagnostic informationlogger.info()- General information about program executionlogger.warning()- Something unexpected happened or potential problemslogger.error()- Serious problems that prevented function execution
- Documentation: All classes require descriptive docstrings explaining purpose
- Naming: Use PascalCase with descriptive names and standard suffixes:
Configurationfor config classesError/Exceptionfor custom exceptionsResolverfor strategy pattern implementationsInterfacefor abstract base classes
- Pydantic Models: Extend
ConfigurationBasefor config,BaseModelfor data models - Abstract Classes: Use ABC for interfaces with
@abstractmethoddecorators - Validation: Use
@model_validatorand@field_validatorfor Pydantic models - Type Hints: Complete type annotations for all class attributes, use specific types, not
Any
- Follow Google Python docstring conventions: https://google.github.io/styleguide/pyguide.html
- Required for all modules, classes, and functions
- Include brief description and detailed sections as needed:
Parameters:for function parametersReturns:for return valuesRaises:for exceptions that may be raisedAttributes:for class attributes (Pydantic models)
tests/
βββ unit/ # Unit tests (pytest)
βββ integration/ # Integration tests (pytest)
βββ e2e/ # End-to-end tests (behave)
βββ features/ # Gherkin feature files
- Required: Use pytest for all unit and integration tests
- Forbidden: Do not use unittest - pytest is the standard for this project
- E2E Tests: Use behave (BDD) framework for end-to-end testing
- Fixtures: Use
conftest.pyfor shared fixtures - Mocking:
pytest-mockfor AsyncMock objects - Common Pattern:
@pytest.fixture(name="prepare_agent_mocks") def prepare_agent_mocks_fixture(mocker): mock_client = mocker.AsyncMock() mock_agent = mocker.AsyncMock() mock_agent._agent_id = "test_agent_id" return mock_client, mock_agent
- Auth Mock:
MOCK_AUTH = ("mock_user_id", "mock_username", False, "mock_token") - Coverage: Unit tests require 60% coverage, integration 10%
- Async tests: Use marker
pytest.mark.asyncio
- Framework: Behave (BDD) with Gherkin feature files
- Step Definitions: In
tests/e2e/features/steps/ - Common Steps: Service status, authentication, HTTP requests
- Test List: Maintained in
tests/e2e/test_list.txt
uv run make test-unit # Unit tests with coverage
uv run make test-integration # Integration tests
uv run make test-e2e # End-to-end testsuv run make format- Auto-format codeuv run make verify- Run all linters- Create unit tests for new code
- Ensure tests pass
- black: Code formatting
- pylint: Static analysis (
source-roots = "src") - pyright: Type checking
- ruff: Fast linter
- pydocstyle: Docstring style
- mypy: Additional type checking
- bandit: Security issue detection
- Never commit secrets/keys
- Use environment variables for sensitive data
IMPORTANT: Always check pyproject.toml for current versions rather than relying on this list:
- FastAPI: Web framework
- Llama Stack: AI integration
- Pydantic: Data validation/serialization
- SQLAlchemy: Database ORM
- Kubernetes: K8s auth integration
PR titles MUST start with a JIRA issue key prefix. CI enforces this via pr-title-checker (config: .github/pr-title-checker-config.json).
Allowed prefixes: LCORE-, RSPEED-, MGTM-, OLS-, RHIDP-, LEADS-, CWFHEALTH-, [release/
- β
RSPEED-2849: add user_agent to ResponsesEventData - β
feat(observability): add user_agent to ResponsesEventData
- Use
uv sync --group dev --group llslibdevfor dependencies - Always use
uv runprefix for commands - ALWAYS check
pyproject.tomlfor existing dependencies and versions before adding new ones - Follow existing code patterns in the module you're modifying
- Write unit tests covering new functionality
- Run format and verify before completion