~/wiki

Streamlit UI

Confiance : high
streamlitpython-uiweb-appsdata-scienceinteractive-dashboardssession-statecachingrapid-prototyping

Python framework for building interactive web applications with minimal code, particularly popular for data science and AI applications. Provides declarative syntax for creating dashboards, chat interfaces, and data visualization tools.

Core Concepts

Session State Management

Streamlit's session state enables persistent data across page reloads:

  • Session variables: Storing user inputs, loaded data, and application state
  • Initialization patterns: Bootstrap state containers for predictable behavior
  • State synchronization: Keeping UI elements in sync with underlying data
  • Reset mechanisms: Clear session functionality for new user workflows

Caching Strategies

Performance optimization through intelligent data caching:

  • @st.cache_data: Cache expensive computations and data loading
  • @st.cache_resource: Persist model instances and database connections
  • Cache invalidation: Strategic cache clearing for data updates
  • Memory management: Controlling cache size and persistence

RAG Application Patterns

Chat Interface Implementation

The assistant-rh project demonstrates effective Streamlit patterns for RAG applications:

State Bootstrap

# Initialize structured state for predictable chat behavior
if 'messages' not in st.session_state:
    st.session_state.messages = []
if 'sources' not in st.session_state:
    st.session_state.sources = []
if 'rag_chunks' not in st.session_state:
    st.session_state.rag_chunks = []

Document Management

  • Upload handling: File processing with inline context vs. collection creation
  • Document context: Session-persistent document state for retrieval
  • Collection management: Multiple RAG collection picker with pill displays
  • Removal controls: Clean document removal with state synchronization

Parameter Controls

  • Model selection: Dropdown filtered by rate limits and availability
  • RAG configuration: Toggle switches, search method selection, result limits
  • Sampling controls: Temperature sliders, max token limits, seed settings
  • Dynamic updates: Real-time parameter adjustment without page reload

Retriever Integration

CSV Retriever Example

Effective pattern for integrating csv-based-retrieval:

@st.cache_resource
def load_csv_retriever(csv_path):
    return CSVRetriever(csv_path)

# Cached corpus statistics
@st.cache_data
def get_corpus_stats(csv_path):
    return {"total_chunks": len(df), "sources": df['source'].nunique()}

Interface Consistency

  • Standardized chunk objects: Consistent data contracts across retrievers
  • Fallback handling: Graceful degradation when preferred retrievers unavailable
  • Error recovery: User-friendly error messages with recovery suggestions
  • Performance feedback: Loading indicators and operation status

UI Components

Effective sidebar patterns for complex applications:

  • Parameter grouping: Related controls organized in expanders
  • Status indicators: System state, connection status, resource usage
  • Quick actions: Reset buttons, refresh controls, export options
  • Context display: Active document, selected collections, current settings

Message Rendering

Chat interface best practices:

  • Role separation: Distinct styling for user vs. assistant messages
  • Source attribution: Inline pills or links for retrieved information
  • Expandable details: Collapsible sections for chunk previews and metadata
  • Streaming responses: Real-time display of generated text
  • Message persistence: State preservation across page interactions

Result Visualization

  • Chunk display: Formatted text with source metadata
  • Relevance indicators: Scores, rankings, confidence measures
  • Interactive exploration: Clickable chunks for full text view
  • Filtering controls: Dynamic result filtering and sorting

Performance Optimization

Caching Strategies

  • Retriever instances: Cache expensive model/database connections
  • Corpus loading: Single CSV/database read per session
  • Computation results: Cache search results and embeddings
  • UI state: Persist user preferences and session configuration

Memory Management

  • Large dataset handling: Pagination and lazy loading for big corpora
  • Cache limits: Prevent memory bloat with size-based eviction
  • Session cleanup: Clear unused state on navigation or reset
  • Resource monitoring: Track memory usage and performance metrics

Development Benefits

Rapid Prototyping

  • Low code overhead: Minimal boilerplate for functional applications
  • Immediate feedback: Hot reloading during development
  • No frontend expertise: Python developers can build web UIs
  • Component library: Rich set of built-in widgets and displays

Integration Flexibility

  • Python ecosystem: Seamless integration with ML/AI libraries
  • Database connectivity: Direct connection to various data sources
  • API integration: Easy REST/GraphQL client implementation
  • Deployment options: Cloud, container, and local deployment support

Limitations and Considerations

Scalability Constraints

  • Single-user design: Not optimized for high-concurrency applications
  • State management: Session state doesn't scale to multi-user scenarios
  • Real-time updates: Limited WebSocket and real-time event support
  • Custom styling: Limited CSS customization compared to React/Vue

Production Deployment

  • Authentication: Basic auth options, limited enterprise features
  • Security: Careful handling of sensitive data and API keys
  • Performance: Single-threaded execution can limit scalability
  • Monitoring: Basic logging, limited APM integration options

See also