Skip to content

Latest commit

Β 

History

History
399 lines (368 loc) Β· 31.2 KB

File metadata and controls

399 lines (368 loc) Β· 31.2 KB

Lightspeed Core Stack Development Guide

Project Overview

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.

Development Environment

  • Python: Check pyproject.toml for supported Python versions
  • Package Manager: uv (use uv run for 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)

Code Architecture & Patterns

Project Structure

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

Coding Standards

Imports & Dependencies

  • 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.toml for existing dependencies before adding new ones
  • ALWAYS verify current library versions in pyproject.toml rather than assuming versions
  • Check constants.py for shared constants before defining new ones

Module Standards

  • All modules start with descriptive docstrings explaining purpose
  • Use logger = get_logger(__name__) from log.py for module logging
  • Package __init__.py files contain brief package descriptions
  • Central constants.py for shared constants with descriptive comments
  • Type aliases defined at module level for clarity
  • Use Final[type] as type hint for all constants

Configuration

  • All config uses Pydantic models extending ConfigurationBase
  • Base class sets extra="forbid" to reject unknown fields
  • Use @field_validator and @model_validator for custom validation
  • Type hints: Optional[FilePath], PositiveInt, SecretStr

Function Standards

  • Documentation: All functions require docstrings with brief descriptions
  • Type Annotations: Complete type annotations for parameters and return types
    • Use typing_extensions.Self for model validators
    • Union types: str | int (modern syntax)
    • Optional: Optional[Type]
  • 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 def for I/O operations and external API calls
  • Error Handling:
    • Use FastAPI HTTPException with appropriate status codes for API endpoints
    • Handle APIConnectionError from Llama Stack

Logging Standards

  • Use from log import get_logger and module logger pattern: logger = get_logger(__name__)
  • Standard log levels with clear purposes:
    • logger.debug() - Detailed diagnostic information
    • logger.info() - General information about program execution
    • logger.warning() - Something unexpected happened or potential problems
    • logger.error() - Serious problems that prevented function execution

Class Standards

  • Documentation: All classes require descriptive docstrings explaining purpose
  • Naming: Use PascalCase with descriptive names and standard suffixes:
    • Configuration for config classes
    • Error/Exception for custom exceptions
    • Resolver for strategy pattern implementations
    • Interface for abstract base classes
  • Pydantic Models: Extend ConfigurationBase for config, BaseModel for data models
  • Abstract Classes: Use ABC for interfaces with @abstractmethod decorators
  • Validation: Use @model_validator and @field_validator for Pydantic models
  • Type Hints: Complete type annotations for all class attributes, use specific types, not Any

Docstring Standards

  • 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 parameters
    • Returns: for return values
    • Raises: for exceptions that may be raised
    • Attributes: for class attributes (Pydantic models)

Testing Framework

Test Structure

tests/
β”œβ”€β”€ unit/                # Unit tests (pytest)
β”œβ”€β”€ integration/         # Integration tests (pytest)
└── e2e/                 # End-to-end tests (behave)
    └── features/        # Gherkin feature files

Testing Framework Requirements

  • 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

Unit Tests (pytest)

  • Fixtures: Use conftest.py for shared fixtures
  • Mocking: pytest-mock for 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

E2E Tests (behave)

  • 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

Test Commands

uv run make test-unit        # Unit tests with coverage
uv run make test-integration # Integration tests
uv run make test-e2e         # End-to-end tests

Quality Assurance

Required Before Completion

  1. uv run make format - Auto-format code
  2. uv run make verify - Run all linters
  3. Create unit tests for new code
  4. Ensure tests pass

Linting Tools

  • black: Code formatting
  • pylint: Static analysis (source-roots = "src")
  • pyright: Type checking
  • ruff: Fast linter
  • pydocstyle: Docstring style
  • mypy: Additional type checking

Security

  • bandit: Security issue detection
  • Never commit secrets/keys
  • Use environment variables for sensitive data

Key Dependencies

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

Pull Request Requirements

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

Development Workflow

  1. Use uv sync --group dev --group llslibdev for dependencies
  2. Always use uv run prefix for commands
  3. ALWAYS check pyproject.toml for existing dependencies and versions before adding new ones
  4. Follow existing code patterns in the module you're modifying
  5. Write unit tests covering new functionality
  6. Run format and verify before completion