Skip to content

Application API

app.py is the user-interface shell for Boo that coordinates model selection, mode selection, user inputs, uploaded files, provider routing, result rendering, and session-state persistence.

Module Responsibilities

The application module normally owns the following responsibilities:

Area Responsibility
Page setup Configure Streamlit page metadata, layout, title, branding, and top-level containers.
Navigation Render tabs, expanders, sidebars, model selectors, mode selectors, and workflow controls.
Session state Initialize, read, and update st.session_state keys used across reruns.
Provider routing Dispatch user requests to gpt.py, gemini.py, or grok.py based on selected provider/model.
Input handling Read text prompts, uploaded documents, URLs, audio files, images, and workflow options.
Output rendering Display responses, errors, metrics, tables, images, files, and downloadable artifacts.
Error handling Convert runtime exceptions into clear user-facing messages and developer-friendly logs.

Streamlit Import Warning

Streamlit application files often execute UI code at import time. That can make direct mkdocstrings documentation fragile because MkDocs imports the module during the build.

If this page causes mkdocs build to fail, remove app temporarily and document import-safe helper modules instead. A better long-term design is to move reusable application logic into modules that do not render Streamlit widgets at import time.

Recommended import-safe module candidates include:

src/app_services.py
src/session_state.py
src/provider_router.py
src/rendering.py
src/file_services.py

Session-State Contract

The application should use explicit session-state keys for values that must survive Streamlit reruns. The exact keys depend on the current source code, but the application should generally separate these categories:

State Category Example Keys
Selection state selected_model_name, selected_mode_name, selected_provider_name
Input state prompt_text, uploaded_files, uploaded_documents, allow_domains
Intermediate state parsed_documents, chunked_documents, embedding_results
Provider state provider_client_status, vector_store_id, file_ids
Output state chat_response, image_response, audio_response, dataframe_response
UI state active_tab, show_advanced_options, sidebar_expanded

Session-state keys should be written before they are read. Keys should not be reused for unrelated data structures.

Workflow Routing

A typical application workflow should follow this pattern:

  1. Read the selected provider, model, and mode from Streamlit controls.
  2. Validate required user inputs for the selected mode.
  3. Instantiate or call the correct provider wrapper.
  4. Execute the provider method.
  5. Normalize the result for display.
  6. Save the result to session state if it is needed after rerun.
  7. Render the result in the appropriate UI panel.

Documentation Guidance

Public helper functions in app.py should use Google-style docstrings so they can be rendered by MkDocs when the module is import-safe.

A recommended docstring pattern is:

def render_text_mode( selected_model_name: str ) -> None:
    """
    Purpose:
        Render the text-generation workflow for the selected model.

    Args:
        selected_model_name (str): Name of the model selected in the Streamlit UI.

    Returns:
        None: Writes Streamlit controls and output directly to the page.
    """

API Reference

The section below is generated from the source module when mkdocs build runs.

app


Assembly:                Boo
Filename:                app.py
Author:                  Terry D. Eppler
Created:                 05-31-2024

Last Modified By:        Terry D. Eppler
Last Modified On:        05-01-2025

       Boo is a data analysis tool integrating various Generative GPT, Text-Processing, and
       Machine-Learning algorithms for federal analysts.
       Copyright ©  2022  Terry Eppler

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

You can contact me at: terryeppler@gmail.com or eppler.terry@epa.gov

app.py

throw_if

throw_if(name: str, value: object) -> None

Throw if.

Purpose

Validates that a required argument contains a usable value before the surrounding workflow continues. This guard centralizes early validation so provider wrappers and UI routines fail with consistent, readable error messages.

Parameters:

Name Type Description Default
name str

Name value used by the operation.

required
value object

Value value used by the operation.

required

Returns:

Name Type Description
None None

This function performs its work through side effects and does not return a value.

Source code in app.py
def throw_if( name: str, value: object ) -> None:
	"""Throw if.

	Purpose:
	    Validates that a required argument contains a usable value before the surrounding workflow
	    continues. This guard centralizes early validation so provider wrappers and UI routines
	    fail
	    with consistent, readable error messages.

	Args:
	    name (str): Name value used by the operation.
	    value (object): Value value used by the operation.

	Returns:
	    None: This function performs its work through side effects and does not return a value."""
	if value is None:
		raise ValueError( f'Argument "{name}" cannot be None.' )

	if isinstance( value, str ) and not value.strip( ):
		raise ValueError( f'Argument "{name}" cannot be empty.' )

get_runtime_config_value

get_runtime_config_value(
    session_key: str, config_name: str, env_name: str
) -> str

Get runtime config value.

Purpose

Returns normalized information for the application component. The method provides a stable view of provider capabilities, stored state, or response metadata so UI controls and downstream logic can consume it consistently.

Parameters:

Name Type Description Default
session_key str

Session key value used by the operation.

required
config_name str

Config name value used by the operation.

required
env_name str

Env name value used by the operation.

required

Returns:

Name Type Description
str str

Return value produced by the operation.

Source code in app.py
def get_runtime_config_value( session_key: str, config_name: str, env_name: str ) -> str:
	"""Get runtime config value.

	Purpose:
	    Returns normalized information for the application component. The method provides a stable
	    view
	    of provider capabilities, stored state, or response metadata so UI controls and downstream
	    logic
	    can consume it consistently.

	Args:
	    session_key (str): Session key value used by the operation.
	    config_name (str): Config name value used by the operation.
	    env_name (str): Env name value used by the operation.

	Returns:
	    str: Return value produced by the operation."""
	session_value = st.session_state.get( session_key, '' )
	config_value = getattr( cfg, config_name, None )
	env_value = os.environ.get( env_name, '' )

	if session_value:
		return str( session_value ).strip( )

	if config_value:
		return str( config_value ).strip( )

	if env_value:
		return str( env_value ).strip( )

	return ''

sync_provider_config

sync_provider_config(
    session_key: str,
    config_name: str,
    env_name: str,
    value: Any,
    provider: Optional[str] = None,
) -> None

Sync provider config.

Purpose

Performs the sync_provider_config workflow using the inputs supplied by the caller and the current runtime configuration. The function keeps this behavior isolated so related UI, provider, and data-processing paths can call it consistently.

Parameters:

Name Type Description Default
session_key str

Session key value used by the operation.

required
config_name str

Config name value used by the operation.

required
env_name str

Env name value used by the operation.

required
value Any

Value value used by the operation.

required
provider Optional[str]

Provider value used by the operation.

None

Returns:

Name Type Description
None None

This function performs its work through side effects and does not return a value.

Source code in app.py
def sync_provider_config( session_key: str, config_name: str, env_name: str, value: Any,
	provider: Optional[ str ] = None ) -> None:
	"""Sync provider config.

	Purpose:
	    Performs the sync_provider_config workflow using the inputs supplied by the caller and the
	    current runtime configuration. The function keeps this behavior isolated so related UI,
	    provider, and data-processing paths can call it consistently.

	Args:
	    session_key (str): Session key value used by the operation.
	    config_name (str): Config name value used by the operation.
	    env_name (str): Env name value used by the operation.
	    value (Any): Value value used by the operation.
	    provider (Optional[str]): Provider value used by the operation.

	Returns:
	    None: This function performs its work through side effects and does not return a value."""
	text = str( value ).strip( ) if value is not None else ''
	st.session_state[ session_key ] = text

	if text:
		os.environ[ env_name ] = text
		setattr( cfg, config_name, text )
	else:
		os.environ.pop( env_name, None )
		setattr( cfg, config_name, None )

	if provider:
		if 'api_keys' not in st.session_state or not isinstance( st.session_state[ 'api_keys' ],
				dict ):
			st.session_state[ 'api_keys' ] = { 'GPT': None, 'Grok': None, 'Gemini': None }

		st.session_state[ 'api_keys' ][ provider ] = text if text else None

init_env_state

init_env_state(
    key: str,
    config_name: str,
    env_name: str,
    provider: Optional[str] = None,
) -> None

Init env state.

Purpose

Performs the init_env_state workflow using the inputs supplied by the caller and the current runtime configuration. The function keeps this behavior isolated so related UI, provider, and data-processing paths can call it consistently.

Parameters:

Name Type Description Default
key str

Key value used by the operation.

required
config_name str

Config name value used by the operation.

required
env_name str

Env name value used by the operation.

required
provider Optional[str]

Provider value used by the operation.

None

Returns:

Name Type Description
None None

This function performs its work through side effects and does not return a value.

Source code in app.py
def init_env_state( key: str, config_name: str, env_name: str,
	provider: Optional[ str ] = None ) -> None:
	"""Init env state.

	Purpose:
	    Performs the init_env_state workflow using the inputs supplied by the caller and the
	    current
	    runtime configuration. The function keeps this behavior isolated so related UI, provider,
	    and
	    data-processing paths can call it consistently.

	Args:
	    key (str): Key value used by the operation.
	    config_name (str): Config name value used by the operation.
	    env_name (str): Env name value used by the operation.
	    provider (Optional[str]): Provider value used by the operation.

	Returns:
	    None: This function performs its work through side effects and does not return a value."""
	init_state( key, '' )
	value = get_runtime_config_value( key, config_name, env_name )
	sync_provider_config( key, config_name, env_name, value, provider )

copy_state_alias

copy_state_alias(
    source_key: str, target_key: str, default: Any
) -> None

Copy state alias.

Purpose

Performs the copy_state_alias workflow using the inputs supplied by the caller and the current runtime configuration. The function keeps this behavior isolated so related UI, provider, and data-processing paths can call it consistently.

Parameters:

Name Type Description Default
source_key str

Source key value used by the operation.

required
target_key str

Target key value used by the operation.

required
default Any

Default value used by the operation.

required

Returns:

Name Type Description
None None

This function performs its work through side effects and does not return a value.

Source code in app.py
def copy_state_alias( source_key: str, target_key: str, default: Any ) -> None:
	"""Copy state alias.

	Purpose:
	    Performs the copy_state_alias workflow using the inputs supplied by the caller and the
	    current
	    runtime configuration. The function keeps this behavior isolated so related UI, provider,
	    and
	    data-processing paths can call it consistently.

	Args:
	    source_key (str): Source key value used by the operation.
	    target_key (str): Target key value used by the operation.
	    default (Any): Default value used by the operation.

	Returns:
	    None: This function performs its work through side effects and does not return a value."""
	if target_key not in st.session_state:
		st.session_state[ target_key ] = st.session_state.get( source_key, default )

	if source_key not in st.session_state:
		st.session_state[ source_key ] = st.session_state.get( target_key, default )

extract_response_text

extract_response_text(response: object) -> str

Extract response text.

Purpose

Extracts structured information from a provider response, uploaded file, or application data object. The function normalizes provider-specific shapes into values that can be rendered, stored, or passed to later processing steps.

Parameters:

Name Type Description Default
response object

Response value used by the operation.

required

Returns:

Name Type Description
str str

Return value produced by the operation.

Source code in app.py
def extract_response_text( response: object ) -> str:
	"""Extract response text.

	Purpose:
	    Extracts structured information from a provider response, uploaded file, or application
	    data  object. The function normalizes provider-specific shapes into values that can be
	    rendered,
	    stored, or passed to later processing steps.

	Args:
	    response (object): Response value used by the operation.

	Returns:
	    str: Return value produced by the operation."""
	if response is None:
		return ""

	output = getattr( response, "output", None )
	if not output or not isinstance( output, list ):
		return ""

	text_chunks: list[ str ] = [ ]

	for item in output:
		if not hasattr( item, "type" ):
			continue

		if item.type == "message":
			content = getattr( item, "content", None )
			if not content or not isinstance( content, list ):
				continue

			for part in content:
				if getattr( part, "type", None ) == "output_text":
					text = getattr( part, "text", "" )
					if text:
						text_chunks.append( text )

	return "".join( text_chunks ).strip( )

encode_image_base64

encode_image_base64(path: str) -> str

Encode image base64.

Purpose

Performs the encode_image_base64 workflow using the inputs supplied by the caller and the current runtime configuration. The function keeps this behavior isolated so related UI, provider, and data-processing paths can call it consistently.

Parameters:

Name Type Description Default
path str

Path value used by the operation.

required

Returns:

Name Type Description
str str

Return value produced by the operation.

Source code in app.py
def encode_image_base64( path: str ) -> str:
	"""Encode image base64.

	Purpose:
	    Performs the encode_image_base64 workflow using the inputs supplied by the caller and the
	    current runtime configuration. The function keeps this behavior isolated so related UI,
	    provider, and data-processing paths can call it consistently.

	Args:
	    path (str): Path value used by the operation.

	Returns:
	    str: Return value produced by the operation."""
	data = Path( path ).read_bytes( )
	return base64.b64encode( data ).decode( "utf-8" )

sanitize_markdown

sanitize_markdown(text: str) -> str

Sanitize markdown.

Purpose

Performs the sanitize_markdown workflow using the inputs supplied by the caller and the current runtime configuration. The function keeps this behavior isolated so related UI, provider, and data-processing paths can call it consistently.

Parameters:

Name Type Description Default
text str

Text value used by the operation.

required

Returns:

Name Type Description
str str

Return value produced by the operation.

Source code in app.py
def sanitize_markdown( text: str ) -> str:
	"""Sanitize markdown.

	Purpose:
	    Performs the sanitize_markdown workflow using the inputs supplied by the caller and the
	    current runtime configuration. The function keeps this behavior isolated so related UI,
	    provider,
	    and data-processing paths can call it consistently.

	Args:
	    text (str): Text value used by the operation.

	Returns:
	    str: Return value produced by the operation."""
	# Remove bold markers
	text = re.sub( r"\*\*(.*?)\*\*", r"\1", text )
	# Optional: remove italics
	text = re.sub( r"\*(.*?)\*", r"\1", text )
	return text

init_state

init_state() -> None

Init state.

Purpose

Performs the init_state workflow using the inputs supplied by the caller and the current runtime configuration. The function keeps this behavior isolated so related UI, provider, and data-processing paths can call it consistently.

Returns:

Name Type Description
None None

This function performs its work through side effects and does not return a value.

Source code in app.py
def init_state( ) -> None:
	"""Init state.

	Purpose:
	    Performs the init_state workflow using the inputs supplied by the caller and the current
	    runtime configuration. The function keeps this behavior isolated so related UI, provider,
	    and
	    data-processing paths can call it consistently.

	Returns:
	    None: This function performs its work through side effects and does not return a value."""
	if 'chat_history' not in st.session_state:
		st.session_state.chat_history = [ ]

	if 'chat_messages' not in st.session_state:
		st.session_state.chat_messages = [ ]

	if 'execution_mode' not in st.session_state:
		st.session_state.execution_mode = 'Standard'

	for k in ('audio_system_instructions', 'image_system_instructions',
		'docqna_system_instructions', 'text_system_instructions'):
		st.session_state.setdefault( k, "" )

reset_state

reset_state() -> None

Reset state.

Purpose

Removes or resets the requested application state or provider resource in a controlled manner. The function keeps cleanup behavior centralized so callers do not duplicate lifecycle logic.

Returns:

Name Type Description
None None

This function performs its work through side effects and does not return a value.

Source code in app.py
def reset_state( ) -> None:
	"""Reset state.

	Purpose:
	    Removes or resets the requested application state or provider resource in a controlled
	    manner.  The function keeps cleanup behavior centralized so callers do not duplicate
	    lifecycle
	    logic.

	Returns:
	    None: This function performs its work through side effects and does not return a value."""
	st.session_state.chat_history = [ ]
	st.session_state.last_answer = ""
	st.session_state.last_sources = [ ]
	st.session_state.last_analysis = { 'tables': [ ], 'files': [ ], 'text': [ ], }

extract_answer

extract_answer(response: Any) -> str

Extract answer.

Purpose

Extracts structured information from a provider response, uploaded file, or application data object. The function normalizes provider-specific shapes into values that can be rendered, stored, or passed to later processing steps.

Parameters:

Name Type Description Default
response Any

Response value used by the operation.

required

Returns:

Name Type Description
str str

Return value produced by the operation.

Source code in app.py
def extract_answer( response: Any ) -> str:
	"""Extract answer.

	Purpose:
	    Extracts structured information from a provider response, uploaded file, or application
	    data object. The function normalizes provider-specific shapes into values that can be
	    rendered,
	    stored, or passed to later processing steps.

	Args:
	    response (Any): Response value used by the operation.

	Returns:
	    str: Return value produced by the operation."""
	texts: List[ str ] = [ ]

	if response is None:
		return ''

	output = getattr( response, 'output', None )
	if not isinstance( output, list ):
		return ''

	for item in output:
		if item is None:
			continue

		item_type = getattr( item, 'type', None )

		# ---------------------------------------
		# Direct text items
		# ---------------------------------------
		if item_type in cfg.TEXT_TYPES:
			text = getattr( item, 'text', None )
			if isinstance( text, str ) and text.strip( ):
				texts.append( text )
			continue

		# ---------------------------------------
		# Nested content blocks
		# ---------------------------------------
		content = getattr( item, 'content', None )
		if not isinstance( content, list ):
			continue

		for block in content:
			if block is None:
				continue

			block_type = getattr( block, 'type', None )
			if block_type in cfg.TEXT_TYPES:
				text = getattr( block, 'text', None )
				if isinstance( text, str ) and text.strip( ):
					texts.append( text )

	return '\n'.join( texts ).strip( )

extract_sources

extract_sources(response: Any) -> List[Dict[str, Any]]

Extract sources.

Purpose

Extracts structured information from a provider response, uploaded file, or application data object. The function normalizes provider-specific shapes into values that can be rendered, stored, or passed to later processing steps.

Parameters:

Name Type Description Default
response Any

Response value used by the operation.

required

Returns:

Type Description
List[Dict[str, Any]]

List[Dict[str, Any]]: Return value produced by the operation.

Source code in app.py
def extract_sources( response: Any ) -> List[ Dict[ str, Any ] ]:
	"""Extract sources.

	Purpose:
	    Extracts structured information from a provider response, uploaded file, or application
	    data object. The function normalizes provider-specific shapes into values that can be
	    rendered,
	    stored, or passed to later processing steps.

	Args:
	    response (Any): Response value used by the operation.

	Returns:
	    List[Dict[str, Any]]: Return value produced by the operation."""
	sources: List[ Dict[ str, Any ] ] = [ ]

	if response is None:
		return sources

	output = getattr( response, 'output', None )
	if not isinstance( output, list ):
		return sources

	for item in output:
		if item is None:
			continue

		t = getattr( item, 'type', None )

		# ------------------------------------------------
		# Web search
		# ------------------------------------------------
		if t == 'web_search_call':
			action = getattr( item, 'action', None )
			raw = getattr( action, 'sources', None ) if action else None

			if not isinstance( raw, (list, tuple) ):
				continue

			for src in raw:
				s = normalize( src )
				if not isinstance( s, dict ):
					continue

				sources.append( { 'title': s.get( 'title' ), 'snippet': s.get( 'snippet' ),
					'url': s.get( 'url' ), 'files_id': None, } )

		# ------------------------------------------------
		# File search (vector store)
		# ------------------------------------------------
		elif t == 'file_search_call':
			raw = getattr( item, 'results', None )

			if not isinstance( raw, (list, tuple) ):
				continue

			for r in raw:
				s = normalize( r )
				if not isinstance( s, dict ):
					continue

				sources.append(
					{ 'title': s.get( 'file_name' ) or s.get( 'title' ), 'snippet': s.get(
						'text' ),
						'url': None, 'files_id': s.get( 'files_id' ), } )

	return sources

extract_analysis

extract_analysis(response: Any) -> Dict[str, Any]

Extract analysis.

Purpose

Extracts structured information from a provider response, uploaded file, or application data object. The function normalizes provider-specific shapes into values that can be rendered, stored, or passed to later processing steps.

Parameters:

Name Type Description Default
response Any

Response value used by the operation.

required

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Return value produced by the operation.

Source code in app.py
def extract_analysis( response: Any ) -> Dict[ str, Any ]:
	"""Extract analysis.

	Purpose:
	    Extracts structured information from a provider response, uploaded file, or application
	    data object. The function normalizes provider-specific shapes into values that can be
	    rendered,
	    stored, or passed to later processing steps.

	Args:
	    response (Any): Response value used by the operation.

	Returns:
	    Dict[str, Any]: Return value produced by the operation."""
	artifacts: Dict[ str, Any ] = { 'tables': [ ], 'files': [ ], 'text': [ ] }

	if response is None:
		return artifacts

	output = getattr( response, 'output', None )
	if not isinstance( output, list ):
		return artifacts

	for item in output:
		if item is None:
			continue

		if getattr( item, 'type', None ) != 'code_interpreter_call':
			continue

		outputs = getattr( item, 'outputs', None )
		if not isinstance( outputs, (list, tuple) ):
			continue

		for out in outputs:
			if out is None:
				continue

			out_type = getattr( out, 'type', None )

			if out_type == 'table':
				normalized = normalize( out )
				artifacts[ 'tables' ].append( normalized )

			elif out_type == 'file':
				normalized = normalize( out )
				artifacts[ 'files' ].append( normalized )

			elif out_type in cfg.TEXT_TYPES:
				text = getattr( out, 'text', None )
				if isinstance( text, str ) and text.strip( ):
					artifacts[ 'text' ].append( text )

	return artifacts

save_temp

save_temp(upload) -> str | None

Save temp.

Purpose

Persists or stages input data so it can be used by later provider or application workflows. The function standardizes file handling and returns a stable reference for downstream processing.

Parameters:

Name Type Description Default
upload object

Upload value used by the operation.

required

Returns:

Type Description
str | None

Optional[str]: Return value produced by the operation.

Source code in app.py
def save_temp( upload ) -> str | None:
	"""Save temp.

	Purpose:
	    Persists or stages input data so it can be used by later provider or application
	    workflows. The function standardizes file handling and returns a stable reference for
	    downstream
	    processing.

	Args:
	    upload (object): Upload value used by the operation.

	Returns:
	    Optional[str]: Return value produced by the operation."""
	if upload is None:
		return None

	try:
		_, ext = os.path.splitext( upload.name )
		ext = ext or ""
		with tempfile.NamedTemporaryFile( delete=False, suffix=ext ) as tmp:
			tmp.write( upload.getbuffer( ) )
			tmp_path = tmp.name

		return tmp_path
	except Exception:
		return None

update_token_counters

update_token_counters(resp: Any) -> None

Update token counters.

Purpose

Performs the update_token_counters workflow using the inputs supplied by the caller and the current runtime configuration. The function keeps this behavior isolated so related UI, provider, and data-processing paths can call it consistently.

Parameters:

Name Type Description Default
resp Any

Resp value used by the operation.

required

Returns:

Name Type Description
None None

This function performs its work through side effects and does not return a value.

Source code in app.py
def update_token_counters( resp: Any ) -> None:
	"""Update token counters.

	Purpose:
	    Performs the update_token_counters workflow using the inputs supplied by the caller and the
	    current runtime configuration. The function keeps this behavior isolated so related UI,
	    provider, and data-processing paths can call it consistently.

	Args:
	    resp (Any): Resp value used by the operation.

	Returns:
	    None: This function performs its work through side effects and does not return a value."""
	usage = _extract_usage_from_response( resp )
	st.session_state.last_call_usage = usage
	st.session_state.token_usage[ "prompt_tokens" ] += usage.get( "prompt_tokens", 0 )
	st.session_state.token_usage[ "completion_tokens" ] += usage.get( "completion_tokens", 0 )
	st.session_state.token_usage[ "total_tokens" ] += usage.get( "total_tokens", 0 )

count_tokens

count_tokens(text: str) -> int

Count tokens.

Purpose

Performs the count_tokens workflow using the inputs supplied by the caller and the current runtime configuration. The function keeps this behavior isolated so related UI, provider, and data-processing paths can call it consistently.

Parameters:

Name Type Description Default
text str

Text value used by the operation.

required

Returns:

Name Type Description
int int

Return value produced by the operation.

Source code in app.py
def count_tokens( text: str ) -> int:
	"""Count tokens.

	Purpose:
	    Performs the count_tokens workflow using the inputs supplied by the caller and the current
	    runtime configuration. The function keeps this behavior isolated so related UI, provider,
	    and
	    data-processing paths can call it consistently.

	Args:
	    text (str): Text value used by the operation.

	Returns:
	    int: Return value produced by the operation."""
	encoding = tiktoken.get_encoding( 'cl100k_base' )
	num_tokens = len( encoding.encode( text ) )
	return num_tokens

normalize_storage_object

normalize_storage_object(value: Any) -> Dict[str, Any]

Normalize storage object.

Purpose

Normalizes incoming values into a predictable representation for application processing. The function reduces provider, user-input, or serialization differences before values are stored or displayed.

Parameters:

Name Type Description Default
value Any

Value value used by the operation.

required

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Return value produced by the operation.

Source code in app.py
def normalize_storage_object( value: Any ) -> Dict[ str, Any ]:
	"""Normalize storage object.

	Purpose:
	    Normalizes incoming values into a predictable representation for application processing.
	    The function reduces provider, user-input, or serialization differences before values are
	    stored or displayed.

	Args:
	    value (Any): Value value used by the operation.

	Returns:
	    Dict[str, Any]: Return value produced by the operation."""
	if value is None:
		return { }

	if isinstance( value, dict ):
		result = dict( value )
	elif hasattr( value, 'model_dump' ):
		try:
			dumped = value.model_dump( )
			result = dumped if isinstance( dumped, dict ) else { 'result': dumped }
		except Exception:
			result = { 'result': str( value ) }
	elif hasattr( value, 'dict' ):
		try:
			dumped = value.dict( )
			result = dumped if isinstance( dumped, dict ) else { 'result': dumped }
		except Exception:
			result = { 'result': str( value ) }
	else:
		result = { }
		for attr_name in [ 'id', 'name', 'display_name', 'description', 'status', 'state',
			'file_counts', 'usage_bytes', 'created_at', 'expires_at', 'metadata', 'deleted',
			'collection_id', 'collection_name', 'collection_description', 'documents_count',
			'document_count', 'file_id', 'filename', 'mime_type', 'size_bytes', 'bytes', ]:
			if hasattr( value, attr_name ):
				result[ attr_name ] = getattr( value, attr_name )

		if not result:
			result = { 'result': str( value ) }

	collection_id = result.get( 'collection_id' ) or result.get( 'id' ) or ''
	collection_name = result.get( 'collection_name' ) or result.get( 'display_name' )
	collection_name = collection_name or result.get( 'name' ) or collection_id or ''
	description = result.get( 'collection_description' ) or result.get( 'description' ) or ''
	status = result.get( 'status' ) or result.get( 'state' ) or ''
	file_counts = result.get( 'file_counts' )
	file_counts = file_counts if file_counts is not None else result.get( 'documents_count' )
	file_counts = file_counts if file_counts is not None else result.get( 'document_count' )
	usage_bytes = result.get( 'usage_bytes' )
	usage_bytes = usage_bytes if usage_bytes is not None else result.get( 'size_bytes' )
	usage_bytes = usage_bytes if usage_bytes is not None else result.get( 'bytes' )
	result[ 'id' ] = str( result.get( 'id' ) or collection_id or '' )
	result[ 'name' ] = str( result.get( 'name' ) or collection_name or '' )
	result[ 'display_name' ] = str( result.get( 'display_name' ) or collection_name or '' )
	result[ 'description' ] = str( result.get( 'description' ) or description or '' )
	result[ 'status' ] = str( status or '' )
	result[ 'file_counts' ] = file_counts if file_counts is not None else ''
	result[ 'usage_bytes' ] = usage_bytes if usage_bytes is not None else ''

	if collection_id:
		result[ 'collection_id' ] = str( collection_id )

	if collection_name:
		result[ 'collection_name' ] = str( collection_name )

	if description:
		result[ 'collection_description' ] = str( description )

	return result

render_storage_metadata

render_storage_metadata(metadata: Dict[str, Any]) -> None

Render storage metadata.

Purpose

Renders the requested user interface element or result block in Streamlit using normalized inputs. The function keeps presentation logic isolated from provider calls and data-processing steps so the screen output remains predictable.

Parameters:

Name Type Description Default
metadata Dict[str, Any]

Metadata value used by the operation.

required

Returns:

Name Type Description
None None

This function performs its work through side effects and does not return a value.

Source code in app.py
def render_storage_metadata( metadata: Dict[ str, Any ] ) -> None:
	"""Render storage metadata.

	Purpose:
	    Renders the requested user interface element or result block in Streamlit using normalized
	    inputs. The function keeps presentation logic isolated from provider calls and
	    data-processing
	    steps so the screen output remains predictable.

	Args:
	    metadata (Dict[str, Any]): Metadata value used by the operation.

	Returns:
	    None: This function performs its work through side effects and does not return a value."""
	if not isinstance( metadata, dict ) or len( metadata ) == 0:
		st.info( 'No metadata loaded yet.' )
		return

	st.json( metadata )

save_uploaded_storage_file

save_uploaded_storage_file(
    uploaded_file: Any,
) -> Optional[str]

Save uploaded storage file.

Purpose

Persists or stages input data so it can be used by later provider or application workflows. The function standardizes file handling and returns a stable reference for downstream processing.

Parameters:

Name Type Description Default
uploaded_file Any

Uploaded file value used by the operation.

required

Returns:

Type Description
Optional[str]

Optional[str]: Return value produced by the operation.

Source code in app.py
def save_uploaded_storage_file( uploaded_file: Any ) -> Optional[ str ]:
	"""Save uploaded storage file.

	Purpose:
	    Persists or stages input data so it can be used by later provider or application
	    workflows. The function standardizes file handling and returns a stable reference for
	    downstream
	    processing.

	Args:
	    uploaded_file (Any): Uploaded file value used by the operation.

	Returns:
	    Optional[str]: Return value produced by the operation."""
	if uploaded_file is None:
		return None

	try:
		return save_temp( uploaded_file )
	except Exception:
		pass

	try:
		suffix = Path( uploaded_file.name ).suffix or '.tmp'
		with tempfile.NamedTemporaryFile( delete=False, suffix=suffix ) as tmp:
			tmp.write( uploaded_file.getvalue( ) )
			return tmp.name
	except Exception:
		return None

normalize_text

normalize_text(text: str) -> str

Normalize text.

Purpose

Normalizes incoming values into a predictable representation for application processing. The function reduces provider, user-input, or serialization differences before values are stored or displayed.

Parameters:

Name Type Description Default
text str

Text value used by the operation.

required

Returns:

Name Type Description
str str

Return value produced by the operation.

Source code in app.py
def normalize_text( text: str ) -> str:
	"""Normalize text.

	Purpose:
	    Normalizes incoming values into a predictable representation for application processing.
	    The function reduces provider, user-input, or serialization differences before values are
	    stored or displayed.

	Args:
	    text (str): Text value used by the operation.

	Returns:
	    str: Return value produced by the operation."""
	if not text:
		return ""

	# Lowercase
	text = text.lower( )

	# Remove punctuation except . ! ?
	text = re.sub( r"[^\w\s\.\!\?]", "", text )

	# Ensure single space after sentence delimiters
	text = re.sub( r"([.!?])\s*", r"\1 ", text )

	# Normalize whitespace
	text = re.sub( r"\s+", " ", text ).strip( )

	return text

convert_xml

convert_xml(text: str) -> str

Convert xml.

Purpose

Performs the convert_xml workflow using the inputs supplied by the caller and the current runtime configuration. The function keeps this behavior isolated so related UI, provider, and data-processing paths can call it consistently.

Parameters:

Name Type Description Default
text str

Text value used by the operation.

required

Returns:

Name Type Description
str str

Return value produced by the operation.

Source code in app.py
def convert_xml( text: str ) -> str:
	"""Convert xml.

	Purpose:
	    Performs the convert_xml workflow using the inputs supplied by the caller and the current
	    runtime configuration. The function keeps this behavior isolated so related UI, provider,
	    and data-processing paths can call it consistently.

	Args:
	    text (str): Text value used by the operation.

	Returns:
	    str: Return value produced by the operation."""
	markdown_blocks: List[ str ] = [ ]
	for match in cfg.XML_BLOCK_PATTERN.finditer( text ):
		raw_tag: str = match.group( "tag" )
		body: str = match.group( "body" ).strip( )

		# Humanize tag name for Markdown heading
		heading: str = raw_tag.replace( "_", " " ).replace( "-", " " ).title( )
		markdown_blocks.append( f"## {heading}" )
		if body:
			markdown_blocks.append( body )
	return "\n\n".join( markdown_blocks )

convert_markdown

convert_markdown(text: Any) -> str

Convert markdown.

Purpose

Performs the convert_markdown workflow using the inputs supplied by the caller and the current runtime configuration. The function keeps this behavior isolated so related UI, provider, and data-processing paths can call it consistently.

Parameters:

Name Type Description Default
text Any

Text value used by the operation.

required

Returns:

Name Type Description
str str

Return value produced by the operation.

Source code in app.py
def convert_markdown( text: Any ) -> str:
	"""Convert markdown.

	Purpose:
	    Performs the convert_markdown workflow using the inputs supplied by the caller and the
	    current runtime configuration. The function keeps this behavior isolated so related UI,
	    provider,
	    and data-processing paths can call it consistently.

	Args:
	    text (Any): Text value used by the operation.

	Returns:
	    str: Return value produced by the operation."""
	if not isinstance( text, str ) or not text.strip( ):
		return ""

	# Normalize newlines
	src = text.replace( "\r\n", "\n" ).replace( "\r", "\n" )

	htag_pattern = re.compile( r"<h([1-6])>(.*?)</h\1>", flags=re.IGNORECASE | re.DOTALL )
	md_heading_pattern = re.compile( r"^(#{1,6})[ \t]+(.+?)[ \t]*$", flags=re.MULTILINE )

	# ------------------------------------------------------------------
	# Direction detection
	# ------------------------------------------------------------------
	contains_htags = bool( htag_pattern.search( src ) )

	# ------------------------------------------------------------------
	# XML-like heading tags -> Markdown headings
	# ------------------------------------------------------------------
	if contains_htags:
		def _htag_to_md( match: re.Match ) -> str:
			level = int( match.group( 1 ) )
			content = match.group( 2 ).strip( )

			# Preserve inner newlines safely by collapsing interior whitespace
			# while keeping content readable.
			content = re.sub( r"[ \t]+\n", "\n", content )
			content = re.sub( r"\n[ \t]+", "\n", content )

			return f"{'#' * level} {content}"

		out = htag_pattern.sub( _htag_to_md, src )
		return out.strip( )

	# ------------------------------------------------------------------
	# Markdown headings -> XML-like heading tags
	# ------------------------------------------------------------------
	def _md_to_htag( match: re.Match ) -> str:
		hashes = match.group( 1 )
		content = match.group( 2 ).strip( )
		level = len( hashes )
		return f"<h{level}>{content}</h{level}>"

	out = md_heading_pattern.sub( _md_to_htag, src )
	return out.strip( )

inject_response_css

inject_response_css() -> None

Inject response css.

Purpose

Performs the inject_response_css workflow using the inputs supplied by the caller and the current runtime configuration. The function keeps this behavior isolated so related UI, provider, and data-processing paths can call it consistently.

Returns:

Name Type Description
None None

This function performs its work through side effects and does not return a value.

Source code in app.py
def inject_response_css( ) -> None:
	"""Inject response css.

	Purpose:
	    Performs the inject_response_css workflow using the inputs supplied by the caller and the
	    current runtime configuration. The function keeps this behavior isolated so related UI,
	    provider, and data-processing paths can call it consistently.

	Returns:
	    None: This function performs its work through side effects and does not return a value."""
	st.markdown( """
		<style>
		/* Chat message text */
		.stChatMessage p {
			color: rgb(220, 220, 220);
			font-size: 1rem;
			line-height: 1.6;
		}

		/* Headings inside chat responses */
		.stChatMessage h1 {
			color: rgb(0, 120, 252); /* DoD Blue */
			font-size: 1.6rem;
		}

		.stChatMessage h2 {
			color: rgb(0, 120, 252);
			font-size: 1.35rem;
		}

		.stChatMessage h3 {
			color: rgb(0, 120, 252);
			font-size: 1.15rem;
		}

		.stChatMessage a {
			color: rgb(0, 120, 252); /* DoD Blue */
			text-decoration: underline;
		}

		.stChatMessage a:hover {
			color: rgb(80, 160, 255);
		}

		</style>
		""", unsafe_allow_html=True )

style_subheaders

style_subheaders() -> None

Style subheaders.

Purpose

Performs the style_subheaders workflow using the inputs supplied by the caller and the current runtime configuration. The function keeps this behavior isolated so related UI, provider, and data-processing paths can call it consistently.

Returns:

Name Type Description
None None

This function performs its work through side effects and does not return a value.

Source code in app.py
def style_subheaders( ) -> None:
	"""Style subheaders.

	Purpose:
	    Performs the style_subheaders workflow using the inputs supplied by the caller and the
	    current  runtime configuration. The function keeps this behavior isolated so related UI,
	    provider,
	    and data-processing paths can call it consistently.

	Returns:
	    None: This function performs its work through side effects and does not return a value."""
	st.markdown( """
		<style>
		div[data-testid="stMarkdownContainer"] h2,
		div[data-testid="stMarkdownContainer"] h3,
		div[data-testid="stChatMessage"] div[data-testid="stMarkdownContainer"] h2,
		div[data-testid="stChatMessage"] div[data-testid="stMarkdownContainer"] h3 {
			color: rgb(0, 120, 252) !important;
		}
		</style>
		""", unsafe_allow_html=True, )

apply_gemini_runtime_config

apply_gemini_runtime_config() -> None

Apply gemini runtime config.

Purpose

Supports the apply gemini runtime config application workflow by coordinating validated inputs, Streamlit session state, provider configuration, and local data processing.

Source code in app.py
def apply_gemini_runtime_config( ) -> None:
	"""Apply gemini runtime config.

	Purpose:
	    Supports the apply gemini runtime config application workflow by coordinating validated
	    inputs, Streamlit session state, provider configuration, and local data processing.
	"""
	key = (st.session_state.get( 'gemini_api_key' ) or st.session_state.get(
		'google_api_key' ) or getattr( cfg, 'GEMINI_API_KEY', None ) or getattr( cfg,
		'GOOGLE_API_KEY', None ) or os.environ.get( 'GEMINI_API_KEY' ) or os.environ.get(
		'GOOGLE_API_KEY' ))

	if key:
		os.environ[ 'GEMINI_API_KEY' ] = key
		os.environ[ 'GOOGLE_API_KEY' ] = key

	for env_name in [ 'GOOGLE_GENAI_USE_VERTEXAI', 'GOOGLE_CLOUD_PROJECT',
		'GOOGLE_CLOUD_PROJECT_ID', 'GOOGLE_CLOUD_LOCATION' ]:
		os.environ.pop( env_name, None )

	for attr_name in [ 'GOOGLE_GENAI_USE_VERTEXAI', 'GOOGLE_CLOUD_PROJECT',
		'GOOGLE_CLOUD_PROJECT_ID', 'GOOGLE_CLOUD_LOCATION' ]:
		try:
			setattr( cfg, attr_name, None )
		except Exception as e:
			exception = Error( e )
			exception.module = 'app'
			exception.cause = 'apply_gemini_runtime_config'
			exception.method = 'apply_gemini_runtime_config( ) -> None'
			Logger( ).write( exception )
			pass

extract_text_from_bytes

extract_text_from_bytes(file_bytes: bytes) -> str

Extract text from bytes.

Purpose

Extracts structured information from a provider response, uploaded file, or application data object. The function normalizes provider-specific shapes into values that can be rendered, stored, or passed to later processing steps.

Parameters:

Name Type Description Default
file_bytes bytes

File bytes value used by the operation.

required

Returns:

Name Type Description
str str

Return value produced by the operation.

Source code in app.py
def extract_text_from_bytes( file_bytes: bytes ) -> str:
	"""Extract text from bytes.

	Purpose:
	    Extracts structured information from a provider response, uploaded file, or application
	    data object. The function normalizes provider-specific shapes into values that can be
	    rendered,
	    stored, or passed to later processing steps.

	Args:
	    file_bytes (bytes): File bytes value used by the operation.

	Returns:
	    str: Return value produced by the operation."""
	try:
		import fitz  # PyMuPDF

		doc = fitz.open( stream=file_bytes, filetype="pdf" )
		text = ""
		for page in doc:
			text += page.get_text( )
		return text.strip( )

	except Exception:
		try:
			return file_bytes.decode( errors="ignore" )
		except Exception:
			return ""

route_document_query

route_document_query(prompt: str) -> str

Route document query.

Purpose

Performs the route_document_query workflow using the inputs supplied by the caller and the current runtime configuration. The function keeps this behavior isolated so related UI, provider, and data-processing paths can call it consistently.

Parameters:

Name Type Description Default
prompt str

Prompt value used by the operation.

required

Returns:

Name Type Description
str str

Return value produced by the operation.

Raises:

Type Description
Exception

Re-raises exceptions after recording them with the application logger.

Source code in app.py
def route_document_query( prompt: str ) -> str:
	"""Route document query.

	Purpose:
	    Performs the route_document_query workflow using the inputs supplied by the caller and the
	    current runtime configuration. The function keeps this behavior isolated so related UI,
	    provider, and data-processing paths can call it consistently.

	Args:
	    prompt (str): Prompt value used by the operation.

	Returns:
	    str: Return value produced by the operation.

	Raises:
	    Exception: Re-raises exceptions after recording them with the application logger."""
	try:
		throw_if( 'prompt', prompt )
		provider_name = st.session_state.get( 'provider', 'GPT' )
		docqna = get_chat_module( provider_name )
		user_input = build_document_user_input( prompt )

		if not user_input:
			user_input = (prompt or '').strip( )

		model = st.session_state.get( 'docqna_model' )
		if not model:
			model_options = list( getattr( docqna, 'model_options', [ ] ) or [ ] )
			model = model_options[ 0 ] if model_options else None

		if not model:
			raise ValueError(
				f'No Document Q&A model is configured for provider "{provider_name}".' )

		answer = docqna.generate_text( model=model, prompt=user_input,
			temperature=float( st.session_state.get( 'docqna_temperature', 0.0 ) ),
			top_p=float( st.session_state.get( 'docqna_top_percent', 0.95 ) ),
			frequency=float( st.session_state.get( 'docqna_frequency_penalty', 0.0 ) ),
			presence=float( st.session_state.get( 'docqna_presence_penalty', 0.0 ) ),
			max_tokens=int( st.session_state.get( 'docqna_max_tokens', 4096 ) ) or 4096,
			store=bool( st.session_state.get( 'docqna_store', False ) ), stream=False,
			instruct=st.session_state.get( 'docqna_system_instructions', '' ),
			tools=st.session_state.get( 'docqna_tools', [ ] ),
			include=st.session_state.get( 'docqna_include', [ ] ),
			tool_choice=st.session_state.get( 'docqna_tool_choice' ) or None,
			reasoning=st.session_state.get( 'docqna_reasoning' ) or None, )

		if isinstance( answer, str ):
			return answer

		output_text = getattr( docqna, 'output_text', None )
		if isinstance( output_text, str ) and output_text.strip( ):
			return output_text.strip( )

		output_text = getattr( answer, 'output_text', None )
		if isinstance( output_text, str ) and output_text.strip( ):
			return output_text.strip( )

		return str( answer or '' )
	except Exception as e:
		ex = Error( e )
		ex.module = 'app'
		ex.cause = 'Document Q&A'
		ex.method = 'route_document_query( prompt: str ) -> str'
		Logger( ).write( ex )
		raise ex

summarize_active_document

summarize_active_document() -> str

Summarize active document.

Purpose

Performs the summarize_active_document workflow using the inputs supplied by the caller and the current runtime configuration. The function keeps this behavior isolated so related UI, provider, and data-processing paths can call it consistently.

Returns:

Name Type Description
str str

Return value produced by the operation.

Source code in app.py
def summarize_active_document( ) -> str:
	"""Summarize active document.

	Purpose:
	    Performs the summarize_active_document workflow using the inputs supplied by the caller
	    and the current runtime configuration. The function keeps this behavior isolated so
	    related UI,
	    provider, and data-processing paths can call it consistently.

	Returns:
	    str: Return value produced by the operation."""
	system_instructions = st.session_state.get( "system_instructions", "" )
	summary_prompt = """
		Provide a clear, structured summary of this document.
		Include:
		- Purpose
		- Key themes
		- Major conclusions
		- Important data points (if any)
		- Policy implications (if applicable)

		Be precise and concise.
		"""
	if system_instructions:
		summary_prompt = f"{system_instructions}\n\n{summary_prompt}"

	return route_document_query( summary_prompt.strip( ) )

load_embedder

load_embedder() -> SentenceTransformer

Load embedder.

Purpose

Performs the load_embedder workflow using the inputs supplied by the caller and the current runtime configuration. The function keeps this behavior isolated so related UI, provider, and data-processing paths can call it consistently.

Returns:

Name Type Description
SentenceTransformer SentenceTransformer

Return value produced by the operation.

Raises:

Type Description
Exception

Re-raises exceptions after recording them with the application logger.

Source code in app.py
@st.cache_resource( show_spinner=False )
def load_embedder( ) -> SentenceTransformer:
	"""Load embedder.

	Purpose:
	    Performs the load_embedder workflow using the inputs supplied by the caller and the current
	    runtime configuration. The function keeps this behavior isolated so related UI, provider,
	    and
	    data-processing paths can call it consistently.

	Returns:
	    SentenceTransformer: Return value produced by the operation.

	Raises:
	    Exception: Re-raises exceptions after recording them with the application logger."""
	try:
		model_name = 'sentence-transformers/all-MiniLM-L6-v2'
		embedder = SentenceTransformer( model_name )
		if embedder is None:
			raise ValueError( 'The Document Q&A embedder could not be loaded.' )

		return embedder
	except Exception as e:
		exception = Error( e )
		exception.module = 'app'
		exception.cause = 'Document Q&A'
		exception.method = 'load_embedder( ) -> SentenceTransformer'
		Logger( ).write( exception )
		raise exception

retrieve_top_doc_chunks

retrieve_top_doc_chunks(
    query: str, k: int = 6
) -> List[Tuple[str, str, float]]

Retrieve top doc chunks.

Purpose

Performs the retrieve_top_doc_chunks workflow using the inputs supplied by the caller and the current runtime configuration. The function keeps this behavior isolated so related UI, provider, and data-processing paths can call it consistently.

Parameters:

Name Type Description Default
query str

Query value used by the operation.

required
k int

K value used by the operation.

6

Returns:

Type Description
List[Tuple[str, str, float]]

List[Tuple[str, str, float]]: Return value produced by the operation.

Source code in app.py
def retrieve_top_doc_chunks( query: str, k: int = 6 ) -> List[ Tuple[ str, str, float ] ]:
	"""Retrieve top doc chunks.

	Purpose:
	    Performs the retrieve_top_doc_chunks workflow using the inputs supplied by the caller and
	    the
	    current runtime configuration. The function keeps this behavior isolated so related UI,
	    provider, and data-processing paths can call it consistently.

	Args:
	    query (str): Query value used by the operation.
	    k (int): K value used by the operation.

	Returns:
	    List[Tuple[str, str, float]]: Return value produced by the operation."""
	if not query or not query.strip( ):
		return [ ]

	embedder: SentenceTransformer = load_embedder( )
	_docqna_rebuild_index_if_needed( embedder )

	qv = embedder.encode( [ query ], show_progress_bar=False )
	qv = np.asarray( qv, dtype=np.float32 )[ 0 ]

	if st.session_state.get( 'docqna_vec_ready', False ):
		conn = create_connection( )
		try:
			_docqna_safe_load_sqlite_vec( conn )
			cur = conn.cursor( )
			cur.execute( '''
                         SELECT doc_name, chunk, distance
                         FROM docqna_vec
                         WHERE embedding MATCH ?
                         ORDER BY distance ASC LIMIT ?;
			             ''', (qv.tobytes( ), int( k )) )
			rows = cur.fetchall( )
			return [ (r[ 0 ], r[ 1 ], float( r[ 2 ] )) for r in rows ]
		except Exception:
			st.session_state[ 'docqna_vec_ready' ] = False
		finally:
			conn.close( )

	fallback_rows: List[ Tuple[ str, str, bytes ] ] = st.session_state.get( 'docqna_fallback_rows',
		[ ] )
	results: List[ Tuple[ str, str, float ] ] = [ ]

	for doc_name, chunk_text_value, vec_blob in fallback_rows:
		if not vec_blob:
			continue

		v = np.frombuffer( vec_blob, dtype=np.float32 )
		if v.size == 0:
			continue

		score = cosine_sim( qv, v )
		results.append( (doc_name, chunk_text_value, float( score )) )

	results.sort( key=lambda r: r[ 2 ], reverse=True )
	return results[ : int( k ) ]

build_document_user_input

build_document_user_input(
    user_query: str, k: int = 6
) -> str

Build document user input.

Purpose

Builds the normalized data structure required by the application workflow. The function converts caller input, session state, or provider-specific options into a stable shape that downstream API calls and rendering code can consume safely.

Parameters:

Name Type Description Default
user_query str

User query value used by the operation.

required
k int

K value used by the operation.

6

Returns:

Name Type Description
str str

Return value produced by the operation.

Source code in app.py
def build_document_user_input( user_query: str, k: int = 6 ) -> str:
	"""Build document user input.

	Purpose:
	    Builds the normalized data structure required by the application workflow. The function
	    converts
	    caller input, session state, or provider-specific options into a stable shape that
	    downstream
	    API calls and rendering code can consume safely.

	Args:
	    user_query (str): User query value used by the operation.
	    k (int): K value used by the operation.

	Returns:
	    str: Return value produced by the operation."""
	system = str( st.session_state.get( 'system_instructions', '' ) or '' ).strip( )
	hits = retrieve_top_doc_chunks( user_query, k=int( k ) )

	context_blocks: List[ str ] = [ ]
	for doc_name, chunk, score in hits:
		context_blocks.append( f'[Document: {doc_name}]\n{chunk}'.strip( ) )

	context = '\n\n'.join( context_blocks ).strip( )

	prompt_parts: List[ str ] = [ ]

	if system:
		prompt_parts.append( system )

	if context:
		prompt_parts.append(
			'Use the following document excerpts to answer the question. If the excerpts do not '
			'contain the answer, say you do not have enough information.\n\n'
			f'{context}' )

	prompt_parts.append( f'Question:\n{user_query}\n\nAnswer:' )

	return '\n\n'.join( prompt_parts ).strip( )

initialize_database

initialize_database() -> None

Initialize database.

Purpose

Performs the initialize_database workflow using the inputs supplied by the caller and the current runtime configuration. The function keeps this behavior isolated so related UI, provider, and data-processing paths can call it consistently.

Returns:

Name Type Description
None None

This function performs its work through side effects and does not return a value.

Source code in app.py
def initialize_database( ) -> None:
	"""Initialize database.

	Purpose:
	    Performs the initialize_database workflow using the inputs supplied by the caller and the
	    current runtime configuration. The function keeps this behavior isolated so related UI,
	    provider, and data-processing paths can call it consistently.

	Returns:
	    None: This function performs its work through side effects and does not return a value."""
	Path( 'stores/sqlite' ).mkdir( parents=True, exist_ok=True )
	with sqlite3.connect( cfg.DB_PATH ) as conn:
		prompt_table_exists = conn.execute( """
                                            SELECT 1
                                            FROM sqlite_master
                                            WHERE type = 'table'
                                              AND name = 'Prompts';
		                                    """ ).fetchone( ) is not None

		if not prompt_table_exists:
			conn.execute( """
                          CREATE TABLE Prompts
                          (
                              ID       INTEGER NOT NULL PRIMARY KEY,
                              Caption  TEXT    NOT NULL,
                              Name     TEXT    NOT NULL,
                              Category TEXT    NOT NULL,
                              Prompt   TEXT    NOT NULL
                          );
			              """ )
		else:
			prompt_columns = { str( row[ 1 ] ) for row in
				conn.execute( 'PRAGMA table_info("Prompts");' ).fetchall( ) }

			required_columns = { 'ID', 'Caption', 'Name', 'Category', 'Prompt', }
			if prompt_columns != required_columns:
				conn.execute( """
                              CREATE TABLE Prompts_New
                              (
                                  ID       INTEGER NOT NULL PRIMARY KEY,
                                  Caption  TEXT    NOT NULL,
                                  Name     TEXT    NOT NULL,
                                  Category TEXT    NOT NULL,
                                  Prompt   TEXT    NOT NULL
                              );
				              """ )

				source_text_column = (
					'Prompt' if 'Prompt' in prompt_columns else 'Text' if 'Text' in prompt_columns
					else None)

				if source_text_column is not None:
					category_expression = (
						'COALESCE(NULLIF(TRIM(Category), \'\'), \'Uncategorized\')' if 'Category'
						                                                               in
						                                                               prompt_columns else '\'Uncategorized\'')

					conn.execute( f"""
						INSERT INTO Prompts_New
						(
							ID,
							Caption,
							Name,
							Category,
							Prompt
						)
						SELECT
							ID,
							COALESCE(NULLIF(TRIM(Caption), ''), 'Prompt ' || ID),
							COALESCE(NULLIF(TRIM(Name), ''), 'Prompt' || ID),
							{category_expression},
							COALESCE({source_text_column}, '')
						FROM Prompts
						WHERE ID IS NOT NULL;
						""" )

				conn.execute( 'DROP TABLE Prompts;' )
				conn.execute( 'ALTER TABLE Prompts_New RENAME TO Prompts;' )

		conn.execute( """
                      CREATE INDEX IF NOT EXISTS IX_Prompts_Category
                          ON Prompts ( Category );
		              """ )

		conn.execute( """
                      CREATE INDEX IF NOT EXISTS IX_Prompts_Caption
                          ON Prompts ( Caption );
		              """ )

		conn.execute( """
                      CREATE INDEX IF NOT EXISTS IX_Prompts_Name
                          ON Prompts ( Name );
		              """ )

		conn.commit( )

read_table

read_table(
    table: str, limit: int = None, offset: int = 0
) -> DataFrame

Read table.

Purpose

Performs the read_table workflow using the inputs supplied by the caller and the current runtime configuration. The function keeps this behavior isolated so related UI, provider, and data-processing paths can call it consistently.

Parameters:

Name Type Description Default
table str

Table value used by the operation.

required
limit int

Limit value used by the operation.

None
offset int

Offset value used by the operation.

0

Returns:

Type Description
DataFrame

pd.DataFrame: Return value produced by the operation.

Source code in app.py
def read_table( table: str, limit: int = None, offset: int = 0 ) -> pd.DataFrame:
	"""Read table.

	Purpose:
	    Performs the read_table workflow using the inputs supplied by the caller and the current
	    runtime configuration. The function keeps this behavior isolated so related UI, provider,
	    and
	    data-processing paths can call it consistently.

	Args:
	    table (str): Table value used by the operation.
	    limit (int): Limit value used by the operation.
	    offset (int): Offset value used by the operation.

	Returns:
	    pd.DataFrame: Return value produced by the operation."""
	if not table:
		return pd.DataFrame( )

	query = f'SELECT * FROM "{table}"'
	if limit:
		query += f' LIMIT {int( limit )} OFFSET {int( offset )}'

	with create_connection( ) as conn:
		cur = conn.cursor( )
		cur.execute( query )

		raw_columns = [ d[ 0 ] for d in (cur.description or [ ]) ]
		rows = cur.fetchall( )

	seen: Dict[ str, int ] = { }
	columns: List[ str ] = [ ]

	for col in raw_columns:
		name = str( col )
		if name not in seen:
			seen[ name ] = 0
			columns.append( name )
		else:
			seen[ name ] += 1
			columns.append( f'{name}_{seen[ name ]}' )

	def _scalarize( value: Any ) -> Any:
		if value is None or isinstance( value, (str, int, float, bool) ):
			return value

		if isinstance( value, bytes ):
			try:
				return value.decode( 'utf-8' )
			except Exception:
				return value.hex( )

		if isinstance( value, (list, tuple, set, dict) ):
			try:
				return str( normalize( value ) )
			except Exception:
				return str( value )

		if hasattr( value, 'model_dump' ):
			try:
				return str( value.model_dump( ) )
			except Exception:
				return str( value )

		return str( value )

	normalized_rows: List[ Dict[ str, Any ] ] = [ ]
	for row in rows:
		record: Dict[ str, Any ] = { }
		for idx, col in enumerate( columns ):
			record[ col ] = _scalarize( row[ idx ] )
		normalized_rows.append( record )

	return pd.DataFrame( normalized_rows, columns=columns )

render_table

render_table(df: DataFrame) -> None

Render table.

Purpose

Renders the requested user interface element or result block in Streamlit using normalized inputs. The function keeps presentation logic isolated from provider calls and data-processing steps so the screen output remains predictable.

Parameters:

Name Type Description Default
df DataFrame

Df value used by the operation.

required

Returns:

Name Type Description
None None

This function performs its work through side effects and does not return a value.

Source code in app.py
def render_table( df: pd.DataFrame ) -> None:
	"""Render table.

	Purpose:
	    Renders the requested user interface element or result block in Streamlit using normalized
	    inputs. The function keeps presentation logic isolated from provider calls and
	    data-processing
	    steps so the screen output remains predictable.

	Args:
	    df (pd.DataFrame): Df value used by the operation.

	Returns:
	    None: This function performs its work through side effects and does not return a value."""
	if df is None:
		st.info( 'No data available.' )
		return

	try:
		st.data_editor( df, use_container_width=True )
		return
	except Exception:
		pass

	fallback_df = df.copy( )
	fallback_df = fallback_df.where( pd.notnull( fallback_df ), '' )

	for col in fallback_df.columns:
		fallback_df[ col ] = fallback_df[ col ].map(
			lambda x: x if isinstance( x, (str, int, float, bool) ) or x == '' else str( x ) )

	st.markdown( fallback_df.to_html( index=False, escape=True ), unsafe_allow_html=True )

drop_table

drop_table(table: str) -> None

Drop table.

Purpose

Performs the drop_table workflow using the inputs supplied by the caller and the current runtime configuration. The function keeps this behavior isolated so related UI, provider, and data-processing paths can call it consistently.

Parameters:

Name Type Description Default
table str

Table value used by the operation.

required

Returns:

Name Type Description
None None

This function performs its work through side effects and does not return a value.

Source code in app.py
def drop_table( table: str ) -> None:
	"""Drop table.

	Purpose:
	    Performs the drop_table workflow using the inputs supplied by the caller and the current
	    runtime configuration. The function keeps this behavior isolated so related UI, provider,
	    and
	    data-processing paths can call it consistently.

	Args:
	    table (str): Table value used by the operation.

	Returns:
	    None: This function performs its work through side effects and does not return a value."""
	if not table:
		return

	with create_connection( ) as conn:
		conn.execute( f'DROP TABLE IF EXISTS "{table}";' )
		conn.commit( )

create_index

create_index(table: str, column: str) -> None

Create index.

Purpose

Creates the requested resource, connection, schema object, or user interface artifact using validated inputs. The function encapsulates setup details so callers can rely on a consistent resource lifecycle.

Parameters:

Name Type Description Default
table str

Table value used by the operation.

required
column str

Column value used by the operation.

required

Returns:

Name Type Description
None None

This function performs its work through side effects and does not return a value.

Source code in app.py
def create_index( table: str, column: str ) -> None:
	"""Create index.

	Purpose:
	    Creates the requested resource, connection, schema object, or user interface artifact using
	    validated inputs. The function encapsulates setup details so callers can rely on a
	    consistent resource lifecycle.

	Args:
	    table (str): Table value used by the operation.
	    column (str): Column value used by the operation.

	Returns:
	    None: This function performs its work through side effects and does not return a value."""
	if not table or not column:
		return

	# ------------------------------------------------------------------
	# Validate table exists
	# ------------------------------------------------------------------
	tables = list_tables( )
	if table not in tables:
		raise ValueError( 'Invalid table name.' )

	# ------------------------------------------------------------------
	# Validate column exists
	# ------------------------------------------------------------------
	schema = create_schema( table )
	valid_columns = [ col[ 1 ] for col in schema ]

	if column not in valid_columns:
		raise ValueError( 'Invalid column name.' )

	# ------------------------------------------------------------------
	# Sanitize index name (identifier only)
	# ------------------------------------------------------------------
	safe_index_name = re.sub( r"[^0-9a-zA-Z_]+", "_", f"idx_{table}_{column}" )

	# ------------------------------------------------------------------
	# Create index safely (quote identifiers)
	# ------------------------------------------------------------------
	sql = f'CREATE INDEX IF NOT EXISTS "{safe_index_name}" ON "{table}"("{column}");'

	with create_connection( ) as conn:
		conn.execute( sql )
		conn.commit( )

create_visualization

create_visualization(df: DataFrame) -> None

Create visualization.

Purpose

Creates the requested resource, connection, schema object, or user interface artifact using validated inputs. The function encapsulates setup details so callers can rely on a consistent resource lifecycle.

Parameters:

Name Type Description Default
df DataFrame

Df value used by the operation.

required

Returns:

Name Type Description
None None

This function performs its work through side effects and does not return a value.

Source code in app.py
def create_visualization( df: pd.DataFrame ) -> None:
	"""Create visualization.

	Purpose:
	    Creates the requested resource, connection, schema object, or user interface artifact using
	    validated inputs. The function encapsulates setup details so callers can rely on a
	    consistent
	    resource lifecycle.

	Args:
	    df (pd.DataFrame): Df value used by the operation.

	Returns:
	    None: This function performs its work through side effects and does not return a value."""
	st.subheader( 'Visualization Engine' )

	if df is None or df.empty:
		st.info( 'No data available.' )
		return

	df_plot = df.copy( )

	for col in df_plot.columns:
		if df_plot[ col ].dtype == object:
			df_plot[ col ] = df_plot[ col ].map( lambda x: '' if x is None else str( x ) )

	numeric_cols: List[ str ] = [ ]
	for col in df_plot.columns:
		series_num = pd.to_numeric( df_plot[ col ], errors='coerce' )
		if series_num.notna( ).any( ):
			numeric_cols.append( col )

	categorical_cols: List[ str ] = [ col for col in df_plot.columns if col not in numeric_cols ]

	chart = st.selectbox( 'Chart Type',
		[ 'Histogram', 'Bar', 'Line', 'Scatter', 'Box', 'Pie', 'Correlation' ] )

	if chart == 'Histogram':
		if not numeric_cols:
			st.info( 'No numeric columns available.' )
			return

		col = st.selectbox( 'Column', numeric_cols )
		values = pd.to_numeric( df_plot[ col ], errors='coerce' ).dropna( ).tolist( )

		fig = go.Figure( data=[ go.Histogram( x=values ) ] )
		fig.update_layout( xaxis_title=col, yaxis_title='Count' )
		st.plotly_chart( fig, use_container_width=True )

	elif chart == 'Bar':
		if not numeric_cols:
			st.info( 'No numeric columns available.' )
			return

		x = st.selectbox( 'X', df_plot.columns )
		y = st.selectbox( 'Y', numeric_cols )

		x_values = df_plot[ x ].astype( str ).tolist( )
		y_values = pd.to_numeric( df_plot[ y ], errors='coerce' ).fillna( 0 ).tolist( )

		fig = go.Figure( data=[ go.Bar( x=x_values, y=y_values ) ] )
		fig.update_layout( xaxis_title=x, yaxis_title=y )
		st.plotly_chart( fig, use_container_width=True )

	elif chart == 'Line':
		if not numeric_cols:
			st.info( 'No numeric columns available.' )
			return

		x = st.selectbox( 'X', df_plot.columns )
		y = st.selectbox( 'Y', numeric_cols )

		x_values = df_plot[ x ].astype( str ).tolist( )
		y_values = pd.to_numeric( df_plot[ y ], errors='coerce' ).fillna( 0 ).tolist( )

		fig = go.Figure( data=[ go.Scatter( x=x_values, y=y_values, mode='lines' ) ] )
		fig.update_layout( xaxis_title=x, yaxis_title=y )
		st.plotly_chart( fig, use_container_width=True )

	elif chart == 'Scatter':
		if len( numeric_cols ) < 2:
			st.info( 'At least two numeric columns are required.' )
			return

		x = st.selectbox( 'X', numeric_cols, key='viz_scatter_x' )
		y = st.selectbox( 'Y', numeric_cols, key='viz_scatter_y' )

		x_series = pd.to_numeric( df_plot[ x ], errors='coerce' )
		y_series = pd.to_numeric( df_plot[ y ], errors='coerce' )
		mask = x_series.notna( ) & y_series.notna( )

		x_values = x_series[ mask ].tolist( )
		y_values = y_series[ mask ].tolist( )

		fig = go.Figure( data=[ go.Scatter( x=x_values, y=y_values, mode='markers' ) ] )
		fig.update_layout( xaxis_title=x, yaxis_title=y )
		st.plotly_chart( fig, use_container_width=True )

	elif chart == 'Box':
		if not numeric_cols:
			st.info( 'No numeric columns available.' )
			return

		col = st.selectbox( 'Column', numeric_cols, key='viz_box_col' )
		values = pd.to_numeric( df_plot[ col ], errors='coerce' ).dropna( ).tolist( )

		fig = go.Figure( data=[ go.Box( y=values, name=col ) ] )
		fig.update_layout( yaxis_title=col )
		st.plotly_chart( fig, use_container_width=True )

	elif chart == 'Pie':
		if not categorical_cols:
			st.info( 'No categorical columns available.' )
			return

		col = st.selectbox( 'Category Column', categorical_cols )
		counts = df_plot[ col ].astype( str ).value_counts( )

		fig = go.Figure(
			data=[ go.Pie( labels=counts.index.tolist( ), values=counts.values.tolist( ) ) ] )
		st.plotly_chart( fig, use_container_width=True )

	elif chart == 'Correlation':
		if len( numeric_cols ) < 2:
			st.info( 'At least two numeric columns are required.' )
			return

		corr_df = pd.DataFrame( )
		for col in numeric_cols:
			corr_df[ col ] = pd.to_numeric( df_plot[ col ], errors='coerce' )

		corr = corr_df.corr( )

		fig = go.Figure( data=[ go.Heatmap( z=corr.values.tolist( ), x=corr.columns.tolist( ),
			y=corr.index.tolist( ) ) ] )
		st.plotly_chart( fig, use_container_width=True )

get_sqlite_type

get_sqlite_type(dtype) -> str

Get sqlite type.

Purpose

Returns normalized information for the application component. The method provides a stable view of provider capabilities, stored state, or response metadata so UI controls and downstream logic can consume it consistently.

Parameters:

Name Type Description Default
dtype object

Dtype value used by the operation.

required

Returns:

Name Type Description
str str

Return value produced by the operation.

Source code in app.py
def get_sqlite_type( dtype ) -> str:
	"""Get sqlite type.

	Purpose:
	    Returns normalized information for the application component. The method provides a stable
	    view of provider capabilities, stored state, or response metadata so UI controls and
	    downstream
	    logic can consume it consistently.

	Args:
	    dtype (object): Dtype value used by the operation.

	Returns:
	    str: Return value produced by the operation."""
	dtype_str = str( dtype ).lower( )

	# ------------------------------------------------------------------
	# Integer Types (including nullable Int64)
	# ------------------------------------------------------------------
	if 'int' in dtype_str:
		return 'INTEGER'

	# ------------------------------------------------------------------
	# Float Types
	# ------------------------------------------------------------------
	if 'float' in dtype_str:
		return 'REAL'

	# ------------------------------------------------------------------
	# Boolean
	# ------------------------------------------------------------------
	if 'bool' in dtype_str:
		return 'INTEGER'

	# ------------------------------------------------------------------
	# Datetime
	# ------------------------------------------------------------------
	if 'datetime' in dtype_str:
		return 'TEXT'

	# ------------------------------------------------------------------
	# Categorical
	# ------------------------------------------------------------------
	if 'category' in dtype_str:
		return 'TEXT'

	# ------------------------------------------------------------------
	# Default fallback
	# ------------------------------------------------------------------
	return 'TEXT'

create_custom_table

create_custom_table(table_name: str, columns: list) -> None

Create custom table.

Purpose

Creates the requested resource, connection, schema object, or user interface artifact using validated inputs. The function encapsulates setup details so callers can rely on a consistent resource lifecycle.

Parameters:

Name Type Description Default
table_name str

Table name value used by the operation.

required
columns list

Columns value used by the operation.

required

Returns:

Name Type Description
None None

This function performs its work through side effects and does not return a value.

Source code in app.py
def create_custom_table( table_name: str, columns: list ) -> None:
	"""Create custom table.

	Purpose:
	    Creates the requested resource, connection, schema object, or user interface artifact using
	    validated inputs. The function encapsulates setup details so callers can rely on a
	    consistent resource lifecycle.

	Args:
	    table_name (str): Table name value used by the operation.
	    columns (list): Columns value used by the operation.

	Returns:
	    None: This function performs its work through side effects and does not return a value."""
	if not table_name:
		raise ValueError( 'Table name required.' )

	# Validate identifier
	if not re.match( r"^[A-Za-z_][A-Za-z0-9_]*$", table_name ):
		raise ValueError( 'Invalid table name.' )

	col_defs = [ ]

	for col in columns:
		col_name = col[ 'name' ]
		col_type = col[ 'type' ].upper( )

		if not re.match( r"^[A-Za-z_][A-Za-z0-9_]*$", col_name ):
			raise ValueError( f"Invalid column name: {col_name}" )

		definition = f'"{col_name}" {col_type}'

		if col[ 'primary_key' ]:
			definition += ' PRIMARY KEY'
			if col[ 'auto_increment' ] and col_type == 'INTEGER':
				definition += ' AUTOINCREMENT'

		if col[ "not_null" ]:
			definition += " NOT NULL"

		col_defs.append( definition )

	sql = f'CREATE TABLE IF NOT EXISTS "{table_name}" ({", ".join( col_defs )});'

	with create_connection( ) as conn:
		conn.execute( sql )
		conn.commit( )

is_safe_query

is_safe_query(query: str) -> bool

Is safe query.

Purpose

Performs the is_safe_query workflow using the inputs supplied by the caller and the current runtime configuration. The function keeps this behavior isolated so related UI, provider, and data-processing paths can call it consistently.

Parameters:

Name Type Description Default
query str

Query value used by the operation.

required

Returns:

Name Type Description
bool bool

Return value produced by the operation.

Source code in app.py
def is_safe_query( query: str ) -> bool:
	"""Is safe query.

	Purpose:
	    Performs the is_safe_query workflow using the inputs supplied by the caller and the current
	    runtime configuration. The function keeps this behavior isolated so related UI, provider,
	    and data-processing paths can call it consistently.

	Args:
	    query (str): Query value used by the operation.

	Returns:
	    bool: Return value produced by the operation."""
	if not query or not isinstance( query, str ):
		return False

	q = query.strip( ).lower( )

	# ------------------------------------------------------------------
	# Block multiple statements
	# ------------------------------------------------------------------
	if ';' in q[ :-1 ]:
		return False

	# ------------------------------------------------------------------
	# Remove SQL comments
	# ------------------------------------------------------------------
	q = re.sub( r"--.*?$", "", q, flags=re.MULTILINE )
	q = re.sub( r"/\*.*?\*/", "", q, flags=re.DOTALL )
	q = q.strip( )

	# ------------------------------------------------------------------
	# Allowed starting keywords
	# ------------------------------------------------------------------
	allowed_starts = ('select', 'with', 'explain', 'pragma')
	if not q.startswith( allowed_starts ):
		return False

	# ------------------------------------------------------------------
	# Block dangerous keywords anywhere
	# ------------------------------------------------------------------
	blocked_keywords = ('insert ', 'update ', 'delete ', 'drop ', 'alter ', 'create ', 'attach ',
		'detach ', 'vacuum ', 'replace ', 'trigger ')

	for keyword in blocked_keywords:
		if keyword in q:
			return False

	return True

create_identifier

create_identifier(name: str) -> str

Create identifier.

Purpose

Creates the requested resource, connection, schema object, or user interface artifact using validated inputs. The function encapsulates setup details so callers can rely on a consistent resource lifecycle.

Parameters:

Name Type Description Default
name str

Name value used by the operation.

required

Returns:

Name Type Description
str str

Return value produced by the operation.

Source code in app.py
def create_identifier( name: str ) -> str:
	"""Create identifier.

	Purpose:
	    Creates the requested resource, connection, schema object, or user interface artifact using
	    validated inputs. The function encapsulates setup details so callers can rely on a
	    consistent resource lifecycle.

	Args:
	    name (str): Name value used by the operation.

	Returns:
	    str: Return value produced by the operation."""
	if not name or not isinstance( name, str ):
		raise ValueError( 'Invalid Identifier.' )

	safe = re.sub( r'[^0-9a-zA-Z_]', '_', name.strip( ) )
	if not re.match( r'^[A-Za-z_]', safe ):
		safe = f'_{safe}'

	if not safe:
		raise ValueError( 'Invalid identifier after sanitization.' )

	return safe

rename_column

rename_column(
    table_name: str, old_name: str, new_name: str
) -> None

Rename column.

Purpose

Performs the rename_column workflow using the inputs supplied by the caller and the current runtime configuration. The function keeps this behavior isolated so related UI, provider, and data-processing paths can call it consistently.

Parameters:

Name Type Description Default
table_name str

Table name value used by the operation.

required
old_name str

Old name value used by the operation.

required
new_name str

New name value used by the operation.

required

Returns:

Name Type Description
None None

This function performs its work through side effects and does not return a value.

Source code in app.py
def rename_column( table_name: str, old_name: str, new_name: str ) -> None:
	"""Rename column.

	Purpose:
	    Performs the rename_column workflow using the inputs supplied by the caller and the current
	    runtime configuration. The function keeps this behavior isolated so related UI, provider,
	    and data-processing paths can call it consistently.

	Args:
	    table_name (str): Table name value used by the operation.
	    old_name (str): Old name value used by the operation.
	    new_name (str): New name value used by the operation.

	Returns:
	    None: This function performs its work through side effects and does not return a value."""
	if not table_name or not old_name or not new_name:
		return

	with create_connection( ) as conn:
		try:
			conn.execute(
				f'ALTER TABLE "{table_name}" RENAME COLUMN "{old_name}" TO "{new_name}";' )
			conn.commit( )
			return
		except Exception:
			pass

		row = conn.execute( """
                            SELECT sql
                            FROM sqlite_master
                            WHERE type ='table' AND name =?
		                    """, (table_name,) ).fetchone( )

		if not row or not row[ 0 ]:
			raise ValueError( "Table definition not found." )

		create_sql = row[ 0 ]

		indexes = conn.execute( """
                                SELECT sql
                                FROM sqlite_master
                                WHERE type ='index' AND tbl_name=? AND sql IS NOT NULL
		                        """, (table_name,) ).fetchall( )

		schema = conn.execute( f'PRAGMA table_info("{table_name}");' ).fetchall( )
		cols = [ r[ 1 ] for r in schema ]
		if old_name not in cols:
			raise ValueError( "Column not found." )

		mapped_cols = [ (new_name if c == old_name else c) for c in cols ]

		temp_table = f"{table_name}__rebuild_temp"

		col_defs: List[ str ] = [ ]
		pk_cols = [ r for r in schema if int( r[ 5 ] or 0 ) > 0 ]
		single_pk = len( pk_cols ) == 1

		for row in schema:
			col_name = row[ 1 ]
			col_type = row[ 2 ] or ''
			not_null = int( row[ 3 ] or 0 )
			default_value = row[ 4 ]
			pk = int( row[ 5 ] or 0 )

			out_name = new_name if col_name == old_name else col_name
			col_def = f'"{out_name}" {col_type}'.strip( )

			if not_null:
				col_def += ' NOT NULL'

			if default_value is not None:
				col_def += f' DEFAULT {default_value}'

			if single_pk and pk == 1:
				col_def += ' PRIMARY KEY'

			col_defs.append( col_def )

		new_create_sql = f'CREATE TABLE "{temp_table}" ({", ".join( col_defs )});'

		old_select = ", ".join( [ f'"{c}"' for c in cols ] )
		new_insert = ", ".join( [ f'"{c}"' for c in mapped_cols ] )

		conn.execute( "BEGIN" )
		conn.execute( new_create_sql )
		conn.execute(
			f'INSERT INTO "{temp_table}" ({new_insert}) SELECT {old_select} FROM "{table_name}";' )

		conn.execute( f'DROP TABLE "{table_name}";' )
		conn.execute( f'ALTER TABLE "{temp_table}" RENAME TO "{table_name}";' )

		for idx in indexes:
			idx_sql = idx[ 0 ]
			if idx_sql:
				idx_sql = idx_sql.replace( f'"{old_name}"', f'"{new_name}"' )
				conn.execute( idx_sql )

		conn.commit( )

rename_table

rename_table(old_name: str, new_name: str) -> None

Rename table.

Purpose

Performs the rename_table workflow using the inputs supplied by the caller and the current runtime configuration. The function keeps this behavior isolated so related UI, provider, and data-processing paths can call it consistently.

Parameters:

Name Type Description Default
old_name str

Old name value used by the operation.

required
new_name str

New name value used by the operation.

required

Returns:

Name Type Description
None None

This function performs its work through side effects and does not return a value.

Source code in app.py
def rename_table( old_name: str, new_name: str ) -> None:
	"""Rename table.

	Purpose:
	    Performs the rename_table workflow using the inputs supplied by the caller and the current
	    runtime configuration. The function keeps this behavior isolated so related UI, provider,
	    and data-processing paths can call it consistently.

	Args:
	    old_name (str): Old name value used by the operation.
	    new_name (str): New name value used by the operation.

	Returns:
	    None: This function performs its work through side effects and does not return a value."""
	if not old_name or not new_name:
		return

	with create_connection( ) as conn:
		try:
			conn.execute( f'ALTER TABLE "{old_name}" RENAME TO "{new_name}";' )
			conn.commit( )
			return
		except Exception:
			pass

		row = conn.execute( """
                            SELECT sql
                            FROM sqlite_master
                            WHERE type ='table' AND name =?
		                    """, (old_name,) ).fetchone( )

		if not row or not row[ 0 ]:
			raise ValueError( "Table definition not found." )

		create_sql = row[ 0 ]

		indexes = conn.execute( """
                                SELECT sql
                                FROM sqlite_master
                                WHERE type ='index' AND tbl_name=? AND sql IS NOT NULL
		                        """, (old_name,) ).fetchall( )

		open_paren = create_sql.find( "(" )
		if open_paren == -1:
			raise ValueError( "Malformed CREATE TABLE statement." )

		temp_name = f"{new_name}__rebuild_temp"

		conn.execute( "BEGIN" )
		conn.execute( f'CREATE TABLE "{temp_name}" {create_sql[ open_paren: ]}' )

		cols = [ r[ 1 ] for r in conn.execute( f'PRAGMA table_info("{old_name}");' ).fetchall( ) ]
		col_list = ", ".join( [ f'"{c}"' for c in cols ] )

		conn.execute(
			f'INSERT INTO "{temp_name}" ({col_list}) SELECT {col_list} FROM "{old_name}";' )

		conn.execute( f'DROP TABLE "{old_name}";' )
		conn.execute( f'ALTER TABLE "{temp_name}" RENAME TO "{new_name}";' )

		for idx in indexes:
			idx_sql = idx[ 0 ]
			if idx_sql:
				idx_sql = idx_sql.replace( f'ON "{old_name}"', f'ON "{new_name}"' )
				conn.execute( idx_sql )

		conn.commit( )

fetch_prompt_categories

fetch_prompt_categories(mode_name: str) -> List[str]

Fetch prompt categories.

Purpose

Returns populated prompt categories authorized for the selected application mode. Categories retain their configured display order and categories without corresponding database records are excluded.

Parameters:

Name Type Description Default
mode_name str

Application mode used to determine the permitted prompt categories.

required

Returns:

Type Description
List[str]

List[str]: Ordered prompt categories available to the selected mode.

Raises:

Type Description
Exception

Re-raises exceptions after recording them with the application logger.

Source code in app.py
def fetch_prompt_categories( mode_name: str ) -> List[ str ]:
	"""Fetch prompt categories.

	Purpose:
	    Returns populated prompt categories authorized for the selected application mode.
	    Categories retain their configured display order and categories without corresponding
	    database
	    records are excluded.

	Args:
	    mode_name (str): Application mode used to determine the permitted prompt categories.

	Returns:
	    List[str]: Ordered prompt categories available to the selected mode.

	Raises:
	    Exception: Re-raises exceptions after recording them with the application logger.
	"""
	try:
		throw_if( 'mode_name', mode_name )
		permitted_categories = PROMPT_CATEGORY_MODE_MAP.get( mode_name, [ ] )

		if not permitted_categories:
			return [ ]

		placeholders = ', '.join( [ '?' ] * len( permitted_categories ) )

		with sqlite3.connect( cfg.DB_PATH ) as conn:
			rows = conn.execute( f"""
				SELECT DISTINCT Category
				FROM Prompts
				WHERE Category IN ({placeholders})
					AND TRIM(Category) <> '';
				""", tuple( permitted_categories ), ).fetchall( )

		available_categories = { str( row[ 0 ] ).strip( ) for row in rows if
			row and row[ 0 ] is not None and str( row[ 0 ] ).strip( ) }

		return [ category for category in permitted_categories if category in
		                                                          available_categories ]
	except Exception as e:
		ex = Error( e )
		ex.module = 'app'
		ex.cause = 'Prompt Templates'
		ex.method = 'fetch_prompt_categories( mode_name: str ) -> List[ str ]'
		Logger( ).write( ex )
		raise ex

fetch_prompt_options

fetch_prompt_options(category: str) -> List[Dict[str, Any]]

Fetch prompt options.

Purpose

Returns prompt-template identifiers and display metadata for the selected category. The result provides stable numeric identifiers for widget state while preserving captions for presentation.

Parameters:

Name Type Description Default
category str

Prompt category used to filter the available templates.

required

Returns:

Type Description
List[Dict[str, Any]]

List[Dict[str, Any]]: Prompt identifiers and display metadata ordered by caption and

List[Dict[str, Any]]

identifier.

Raises:

Type Description
Exception

Re-raises exceptions after recording them with the application logger.

Source code in app.py
def fetch_prompt_options( category: str ) -> List[ Dict[ str, Any ] ]:
	"""Fetch prompt options.

	Purpose:
	    Returns prompt-template identifiers and display metadata for the selected category. The
	    result provides stable numeric identifiers for widget state while preserving captions for
	    presentation.

	Args:
	    category (str): Prompt category used to filter the available templates.

	Returns:
	    List[Dict[str, Any]]: Prompt identifiers and display metadata ordered by caption and
	    identifier.

	Raises:
	    Exception: Re-raises exceptions after recording them with the application logger.
	"""
	try:
		if not category or not str( category ).strip( ):
			return [ ]

		with sqlite3.connect( cfg.DB_PATH ) as conn:
			rows = conn.execute( """
                                 SELECT ID,
                                        Caption,
                                        Name,
                                        Category
                                 FROM Prompts
                                 WHERE Category = ?
                                 ORDER BY Caption, ID;
			                     """, (str( category ).strip( ),), ).fetchall( )

		return [ { 'ID': int( row[ 0 ] ), 'Caption': str( row[ 1 ] or '' ),
			'Name': str( row[ 2 ] or '' ), 'Category': str( row[ 3 ] or '' ), } for row in rows ]
	except Exception as e:
		ex = Error( e )
		ex.module = 'app'
		ex.cause = 'Prompt Templates'
		ex.method = 'fetch_prompt_options( category: str ) -> List[ Dict[ str, Any ] ]'
		Logger( ).write( ex )
		raise ex

fetch_prompt_by_id

fetch_prompt_by_id(
    prompt_id: int,
) -> Optional[Dict[str, Any]]

Fetch prompt by identifier.

Purpose

Returns the complete prompt-template record associated with a stable numeric identifier. The identifier-based lookup prevents ambiguous template selection when captions or names are duplicated.

Parameters:

Name Type Description Default
prompt_id int

Numeric primary key of the prompt-template record.

required

Returns:

Type Description
Optional[Dict[str, Any]]

Optional[Dict[str, Any]]: Complete prompt-template record when found; otherwise None.

Raises:

Type Description
Exception

Re-raises exceptions after recording them with the application logger.

Source code in app.py
def fetch_prompt_by_id( prompt_id: int ) -> Optional[ Dict[ str, Any ] ]:
	"""Fetch prompt by identifier.

	Purpose:
	    Returns the complete prompt-template record associated with a stable numeric identifier.
	    The identifier-based lookup prevents ambiguous template selection when captions or names
	    are
	    duplicated.

	Args:
	    prompt_id (int): Numeric primary key of the prompt-template record.

	Returns:
	    Optional[Dict[str, Any]]: Complete prompt-template record when found; otherwise None.

	Raises:
	    Exception: Re-raises exceptions after recording them with the application logger.
	"""
	try:
		if prompt_id is None:
			return None

		with sqlite3.connect( cfg.DB_PATH ) as conn:
			cur = conn.execute( """
                                SELECT ID,
                                       Caption,
                                       Name,
                                       Category,
                                       Prompt
                                FROM Prompts
                                WHERE ID = ?;
			                    """, (int( prompt_id ),), )

			row = cur.fetchone( )

			if row is None:
				return None

			return { 'ID': int( row[ 0 ] ), 'Caption': str( row[ 1 ] or '' ),
				'Name': str( row[ 2 ] or '' ), 'Category': str( row[ 3 ] or '' ),
				'Prompt': str( row[ 4 ] or '' ), }
	except Exception as e:
		ex = Error( e )
		ex.module = 'app'
		ex.cause = 'Prompt Templates'
		ex.method = 'fetch_prompt_by_id( prompt_id: int ) -> Optional[ Dict[ str, Any ] ]'
		Logger( ).write( ex )
		raise ex

reset_prompt_template_selection

reset_prompt_template_selection(prompt_id_key: str) -> None

Reset prompt template selection.

Purpose

Clears a mode-specific prompt-template selection when its category changes without modifying the current system-instruction text.

Parameters:

Name Type Description Default
prompt_id_key str

Session-state key storing the selected prompt identifier.

required

Returns:

Name Type Description
None None

This function performs its work through side effects and does not return a value.

Raises:

Type Description
Exception

Re-raises exceptions after recording them with the application logger.

Source code in app.py
def reset_prompt_template_selection( prompt_id_key: str ) -> None:
	"""Reset prompt template selection.

	Purpose:
	    Clears a mode-specific prompt-template selection when its category changes without
	    modifying the current system-instruction text.

	Args:
	    prompt_id_key (str): Session-state key storing the selected prompt identifier.

	Returns:
	    None: This function performs its work through side effects and does not return a value.

	Raises:
	    Exception: Re-raises exceptions after recording them with the application logger.
	"""
	try:
		throw_if( 'prompt_id_key', prompt_id_key )
		st.session_state[ prompt_id_key ] = None
	except Exception as e:
		ex = Error( e )
		ex.module = 'app'
		ex.cause = 'Prompt Templates'
		ex.method = 'reset_prompt_template_selection( prompt_id_key: str ) -> None'
		Logger( ).write( ex )
		raise ex

load_prompt_template

load_prompt_template(
    prompt_id_key: str, instructions_key: str
) -> None

Load prompt template.

Purpose

Loads the selected prompt body into a mode-specific system-instruction field while preserving independent template state across application modes.

Parameters:

Name Type Description Default
prompt_id_key str

Session-state key storing the selected prompt identifier.

required
instructions_key str

Session-state key receiving the selected prompt body.

required

Returns:

Name Type Description
None None

This function performs its work through side effects and does not return a value.

Raises:

Type Description
Exception

Re-raises exceptions after recording them with the application logger.

Source code in app.py
def load_prompt_template( prompt_id_key: str, instructions_key: str, ) -> None:
	"""Load prompt template.

	Purpose:
	    Loads the selected prompt body into a mode-specific system-instruction field while
	    preserving independent template state across application modes.

	Args:
	    prompt_id_key (str): Session-state key storing the selected prompt identifier.
	    instructions_key (str): Session-state key receiving the selected prompt body.

	Returns:
	    None: This function performs its work through side effects and does not return a value.

	Raises:
	    Exception: Re-raises exceptions after recording them with the application logger.
	"""
	try:
		throw_if( 'prompt_id_key', prompt_id_key )
		throw_if( 'instructions_key', instructions_key )

		prompt_id = st.session_state.get( prompt_id_key )

		if prompt_id is None:
			return

		record = fetch_prompt_by_id( int( prompt_id ) )

		if record is None:
			return

		st.session_state[ instructions_key ] = record[ 'Prompt' ]
	except Exception as e:
		ex = Error( e )
		ex.module = 'app'
		ex.cause = 'Prompt Templates'
		ex.method = ('load_prompt_template( prompt_id_key: str, '
		             'instructions_key: str ) -> None')
		Logger( ).write( ex )
		raise ex

format_prompt_option

format_prompt_option(
    prompt_id: int, prompt_options: List[Dict[str, Any]]
) -> str

Format prompt option.

Purpose

Resolves a prompt identifier to its human-readable caption for presentation in a Streamlit selection control.

Parameters:

Name Type Description Default
prompt_id int

Numeric prompt identifier rendered by the selection control.

required
prompt_options List[Dict[str, Any]]

Available prompt records used to resolve the caption.

required

Returns:

Name Type Description
str str

Prompt caption when found; otherwise the numeric identifier as text.

Source code in app.py
def format_prompt_option( prompt_id: int, prompt_options: List[ Dict[ str, Any ] ], ) -> str:
	"""Format prompt option.

	Purpose:
	    Resolves a prompt identifier to its human-readable caption for presentation in a Streamlit
	    selection control.

	Args:
	    prompt_id (int): Numeric prompt identifier rendered by the selection control.
	    prompt_options (List[Dict[str, Any]]): Available prompt records used to resolve the
	        caption.

	Returns:
	    str: Prompt caption when found; otherwise the numeric identifier as text.
	"""
	for option in prompt_options:
		if int( option.get( 'ID', -1 ) ) == int( prompt_id ):
			return str( option.get( 'Caption', prompt_id ) )

	return str( prompt_id )

fetch_prompts_df

fetch_prompts_df() -> DataFrame

Fetch prompts dataframe.

Purpose

Returns prompt-template metadata for management and review without rendering large prompt bodies directly in the primary data grid.

Returns:

Type Description
DataFrame

pd.DataFrame: Prompt-template metadata with a selection column.

Raises:

Type Description
Exception

Re-raises exceptions after recording them with the application logger.

Source code in app.py
def fetch_prompts_df( ) -> pd.DataFrame:
	"""Fetch prompts dataframe.

	Purpose:
	    Returns prompt-template metadata for management and review without rendering large prompt
	    bodies directly in the primary data grid.

	Returns:
	    pd.DataFrame: Prompt-template metadata with a selection column.

	Raises:
	    Exception: Re-raises exceptions after recording them with the application logger.
	"""
	try:
		with sqlite3.connect( cfg.DB_PATH ) as conn:
			df_prompts = pd.read_sql_query( """
                                            SELECT ID,
                                                   Caption,
                                                   Name,
                                                   Category
                                            FROM Prompts
                                            ORDER BY ID DESC;
			                                """, conn, )

		df_prompts.insert( 0, 'Selected', False )
		return df_prompts
	except Exception as e:
		ex = Error( e )
		ex.module = 'app'
		ex.cause = 'Prompt Templates'
		ex.method = 'fetch_prompts_df( ) -> pd.DataFrame'
		Logger( ).write( ex )
		raise ex

insert_prompt

insert_prompt(data: Dict[str, Any]) -> None

Insert prompt.

Purpose

Creates a prompt-template record using the canonical category-aware prompt schema.

Parameters:

Name Type Description Default
data Dict[str, Any]

Prompt-template values containing Caption, Name, Category, and Prompt.

required

Returns:

Name Type Description
None None

This function performs its work through side effects and does not return a value.

Raises:

Type Description
Exception

Re-raises exceptions after recording them with the application logger.

Source code in app.py
def insert_prompt( data: Dict[ str, Any ] ) -> None:
	"""Insert prompt.

	Purpose:
	    Creates a prompt-template record using the canonical category-aware prompt schema.

	Args:
	    data (Dict[str, Any]): Prompt-template values containing Caption, Name, Category,
	        and Prompt.

	Returns:
	    None: This function performs its work through side effects and does not return a value.

	Raises:
	    Exception: Re-raises exceptions after recording them with the application logger.
	"""
	try:
		throw_if( 'data', data )
		with sqlite3.connect( cfg.DB_PATH ) as conn:
			conn.execute( """
                          INSERT INTO Prompts
                          (Caption,
                           Name,
                           Category,
                           Prompt)
                          VALUES (?,
                                  ?,
                                  ?,
                                  ?);
			              """, (str( data[ 'Caption' ] ).strip( ), str( data[ 'Name' ] ).strip( ),
				str( data[ 'Category' ] ).strip( ), str( data[ 'Prompt' ] ),), )
			conn.commit( )
	except Exception as e:
		ex = Error( e )
		ex.module = 'app'
		ex.cause = 'Prompt Templates'
		ex.method = 'insert_prompt( data: Dict[ str, Any ] ) -> None'
		Logger( ).write( ex )
		raise ex

update_prompt

update_prompt(prompt_id: int, data: Dict[str, Any]) -> None

Update prompt.

Purpose

Updates an existing prompt-template record using the canonical category-aware prompt schema.

Parameters:

Name Type Description Default
prompt_id int

Numeric primary key of the prompt-template record.

required
data Dict[str, Any]

Replacement Caption, Name, Category, and Prompt values.

required

Returns:

Name Type Description
None None

This function performs its work through side effects and does not return a value.

Raises:

Type Description
Exception

Re-raises exceptions after recording them with the application logger.

Source code in app.py
def update_prompt( prompt_id: int, data: Dict[ str, Any ] ) -> None:
	"""Update prompt.

	Purpose:
	    Updates an existing prompt-template record using the canonical category-aware prompt
	    schema.

	Args:
	    prompt_id (int): Numeric primary key of the prompt-template record.
	    data (Dict[str, Any]): Replacement Caption, Name, Category, and Prompt values.

	Returns:
	    None: This function performs its work through side effects and does not return a value.

	Raises:
	    Exception: Re-raises exceptions after recording them with the application logger.
	"""
	try:
		throw_if( 'data', data )
		with sqlite3.connect( cfg.DB_PATH ) as conn:
			conn.execute( """
                          UPDATE Prompts
                          SET Caption  = ?,
                              Name     = ?,
                              Category = ?,
                              Prompt   = ?
                          WHERE ID = ?;
			              """, (str( data[ 'Caption' ] ).strip( ), str( data[ 'Name' ] ).strip( ),
				str( data[ 'Category' ] ).strip( ), str( data[ 'Prompt' ] ), int( prompt_id ),), )
			conn.commit( )
	except Exception as e:
		ex = Error( e )
		ex.module = 'app'
		ex.cause = 'Prompt Templates'
		ex.method = ('update_prompt( prompt_id: int, '
		             'data: Dict[ str, Any ] ) -> None')
		Logger( ).write( ex )
		raise ex

delete_prompt

delete_prompt(prompt_id: int) -> None

Delete prompt.

Purpose

Removes the prompt-template record associated with the supplied numeric identifier.

Parameters:

Name Type Description Default
prompt_id int

Numeric primary key of the prompt-template record.

required

Returns:

Name Type Description
None None

This function performs its work through side effects and does not return a value.

Raises:

Type Description
Exception

Re-raises exceptions after recording them with the application logger.

Source code in app.py
def delete_prompt( prompt_id: int ) -> None:
	"""Delete prompt.

	Purpose:
	    Removes the prompt-template record associated with the supplied numeric identifier.

	Args:
	    prompt_id (int): Numeric primary key of the prompt-template record.

	Returns:
	    None: This function performs its work through side effects and does not return a value.

	Raises:
	    Exception: Re-raises exceptions after recording them with the application logger.
	"""
	try:
		with sqlite3.connect( cfg.DB_PATH ) as conn:
			conn.execute( 'DELETE FROM Prompts WHERE ID = ?;', (int( prompt_id ),), )
			conn.commit( )
	except Exception as e:
		ex = Error( e )
		ex.module = 'app'
		ex.cause = 'Prompt Templates'
		ex.method = 'delete_prompt( prompt_id: int ) -> None'
		Logger( ).write( ex )
		raise ex

build_prompt

build_prompt(user_input: str) -> str

Build prompt.

Purpose

Builds the normalized data structure required by the application workflow. The function converts caller input, session state, or provider-specific options into a stable shape that downstream API calls and rendering code can consume safely.

Parameters:

Name Type Description Default
user_input str

User input value used by the operation.

required

Returns:

Name Type Description
str str

Return value produced by the operation.

Raises:

Type Description
Exception

Re-raises exceptions after recording them with the application logger.

Source code in app.py
def build_prompt( user_input: str ) -> str:
	"""Build prompt.

	Purpose:
	    Builds the normalized data structure required by the application workflow. The function
	    converts caller input, session state, or provider-specific options into a stable shape that
	    downstream API calls and rendering code can consume safely.

	Args:
	    user_input (str): User input value used by the operation.

	Returns:
	    str: Return value produced by the operation.

	Raises:
	    Exception: Re-raises exceptions after recording them with the application logger."""
	try:
		throw_if( 'user_input', user_input )
		top_k = int( st.session_state.get( 'text_top_k', 6 ) or 6 )
		system_prompt = str( st.session_state.get( 'system_prompt',
			st.session_state.get( 'instructions', '' ) ) or '' ).strip( )
		basic_docs = st.session_state.get( 'basic_docs', [ ] )
		messages = st.session_state.get( 'messages', [ ] )
		use_semantic = bool( st.session_state.get( 'use_semantic', False ) )
		prompt = ''
		if system_prompt:
			prompt += f'<|system|>\n{system_prompt}\n</s>\n'
		if use_semantic:
			try:
				with sqlite3.connect( cfg.DB_PATH ) as conn:
					rows = conn.execute( 'SELECT chunk, vector FROM embeddings' ).fetchall( )
				if rows:
					embedder = load_embedder( )
					query_vector = embedder.encode( [ user_input ] )[ 0 ]
					query_vector = np.asarray( query_vector, dtype=np.float32 )
					scored = [ ]
					for chunk, vector_blob in rows:
						if chunk is None or vector_blob is None:
							continue

						vector = np.frombuffer( vector_blob, dtype=np.float32 )
						if vector.size != query_vector.size:
							alternate_vector = np.frombuffer( vector_blob, dtype=np.float64 )
							if alternate_vector.size != query_vector.size:
								continue

							vector = alternate_vector.astype( np.float32 )
						score = cosine_sim( query_vector, vector )
						scored.append( (chunk, score) )

					for chunk, _ in sorted( scored, key=lambda item: item[ 1 ], reverse=True )[
						:top_k ]:
						prompt += f'<|system|>\n{chunk}\n</s>\n'
			except Exception:
				pass
		if isinstance( basic_docs, list ):
			for document in basic_docs[ :6 ]:
				if document:
					prompt += f'<|system|>\n{document}\n</s>\n'

		if isinstance( messages, list ):
			for message in messages:
				if isinstance( message, dict ):
					role = message.get( 'role', 'user' )
					content = message.get( 'content', '' )
				elif isinstance( message, (list, tuple) ) and len( message ) >= 2:
					role, content = message[ 0 ], message[ 1 ]
				else:
					continue

				if role and content:
					prompt += f'<|{role}|>\n{content}\n</s>\n'

		prompt += f'<|user|>\n{user_input}\n</s>\n<|assistant|>\n'
		return prompt
	except Exception as e:
		exception = Error( e )
		exception.module = 'app'
		exception.cause = 'Prompt Builder'
		exception.method = 'build_prompt( user_input: str ) -> str'
		Logger( ).write( exception )
		raise exception

get_provider_name

get_provider_name(provider: Optional[str] = None) -> str

Get provider name.

Purpose

Returns normalized information for the application component. The method provides a stable view of provider capabilities, stored state, or response metadata so UI controls and downstream logic can consume it consistently.

Parameters:

Name Type Description Default
provider Optional[str]

Provider value used by the operation.

None

Returns:

Name Type Description
str str

Return value produced by the operation.

Source code in app.py
def get_provider_name( provider: Optional[ str ] = None ) -> str:
	"""Get provider name.

	Purpose:
	    Returns normalized information for the application component. The method provides a stable
	    view of provider capabilities, stored state, or response metadata so UI controls and
	    downstream
	    logic can consume it consistently.

	Args:
	    provider (Optional[str]): Provider value used by the operation.

	Returns:
	    str: Return value produced by the operation."""
	selected = provider or st.session_state.get( 'provider', 'GPT' )
	providers = getattr( cfg, 'PROVIDERS', { 'GPT': 'gpt', 'Gemini': 'gemini', 'Grok': 'grok' } )

	if selected not in providers:
		selected = 'GPT'
		st.session_state[ 'provider' ] = selected

	return selected

get_provider_module

get_provider_module(provider: Optional[str] = None) -> Any

Get provider module.

Purpose

Returns normalized information for the application component. The method provides a stable view of provider capabilities, stored state, or response metadata so UI controls and downstream logic can consume it consistently.

Parameters:

Name Type Description Default
provider Optional[str]

Provider value used by the operation.

None

Returns:

Name Type Description
Any Any

Return value produced by the operation.

Source code in app.py
def get_provider_module( provider: Optional[ str ] = None ) -> Any:
	"""Get provider module.

	Purpose:
	    Returns normalized information for the application component. The method provides a stable
	    view of provider capabilities, stored state, or response metadata so UI controls and
	    downstream
	    logic can consume it consistently.

	Args:
	    provider (Optional[str]): Provider value used by the operation.

	Returns:
	    Any: Return value produced by the operation."""
	selected = get_provider_name( provider )
	provider_modules = { 'GPT': gpt, 'Gemini': gemini, 'Grok': grok, }

	module = provider_modules.get( selected )
	if module is None:
		raise ValueError( f'Provider "{selected}" is not mapped to an imported module.' )

	return module

provider_has_class

provider_has_class(
    class_name: str, provider: Optional[str] = None
) -> bool

Provider has class.

Purpose

Performs the provider_has_class workflow using the inputs supplied by the caller and the current runtime configuration. The function keeps this behavior isolated so related UI, provider, and data-processing paths can call it consistently.

Parameters:

Name Type Description Default
class_name str

Class name value used by the operation.

required
provider Optional[str]

Provider value used by the operation.

None

Returns:

Name Type Description
bool bool

Return value produced by the operation.

Source code in app.py
def provider_has_class( class_name: str, provider: Optional[ str ] = None ) -> bool:
	"""Provider has class.

	Purpose:
	    Performs the provider_has_class workflow using the inputs supplied by the caller and the
	    current runtime configuration. The function keeps this behavior isolated so related UI,
	    provider,
	    and data-processing paths can call it consistently.

	Args:
	    class_name (str): Class name value used by the operation.
	    provider (Optional[str]): Provider value used by the operation.

	Returns:
	    bool: Return value produced by the operation."""
	if not class_name:
		return False

	provider_module = get_provider_module( provider )
	return hasattr( provider_module, class_name )

get_provider_class

get_provider_class(
    class_name: str, provider: Optional[str] = None
) -> type

Get provider class.

Purpose

Returns normalized information for the application component. The method provides a stable view of provider capabilities, stored state, or response metadata so UI controls and downstream logic can consume it consistently.

Parameters:

Name Type Description Default
class_name str

Class name value used by the operation.

required
provider Optional[str]

Provider value used by the operation.

None

Returns:

Name Type Description
type type

Return value produced by the operation.

Source code in app.py
def get_provider_class( class_name: str, provider: Optional[ str ] = None ) -> type:
	"""Get provider class.

	Purpose:
	    Returns normalized information for the application component. The method provides a stable
	    view of provider capabilities, stored state, or response metadata so UI controls and
	    downstream
	    logic can consume it consistently.

	Args:
	    class_name (str): Class name value used by the operation.
	    provider (Optional[str]): Provider value used by the operation.

	Returns:
	    type: Return value produced by the operation."""
	if not class_name:
		raise ValueError( 'class_name cannot be empty.' )

	selected = get_provider_name( provider )
	provider_module = get_provider_module( selected )

	if not hasattr( provider_module, class_name ):
		raise AttributeError(
			f'Provider "{selected}" does not expose a "{class_name}" wrapper class.' )

	return getattr( provider_module, class_name )

get_provider_instance

get_provider_instance(
    class_name: str, provider: Optional[str] = None
) -> Any

Get provider instance.

Purpose

Returns normalized information for the application component. The method provides a stable view of provider capabilities, stored state, or response metadata so UI controls and downstream logic can consume it consistently.

Parameters:

Name Type Description Default
class_name str

Class name value used by the operation.

required
provider Optional[str]

Provider value used by the operation.

None

Returns:

Name Type Description
Any Any

Return value produced by the operation.

Source code in app.py
def get_provider_instance( class_name: str, provider: Optional[ str ] = None ) -> Any:
	"""Get provider instance.

	Purpose:
	    Returns normalized information for the application component. The method provides a stable
	    view of provider capabilities, stored state, or response metadata so UI controls and
	    downstream
	    logic can consume it consistently.

	Args:
	    class_name (str): Class name value used by the operation.
	    provider (Optional[str]): Provider value used by the operation.

	Returns:
	    Any: Return value produced by the operation."""
	provider_class = get_provider_class( class_name, provider )
	return provider_class( )

get_chat_module

get_chat_module(provider: Optional[str] = None) -> Any

Get chat module.

Purpose

Returns normalized information for the application component. The method provides a stable view of provider capabilities, stored state, or response metadata so UI controls and downstream logic can consume it consistently.

Parameters:

Name Type Description Default
provider Optional[str]

Provider value used by the operation.

None

Returns:

Name Type Description
Any Any

Return value produced by the operation.

Source code in app.py
def get_chat_module( provider: Optional[ str ] = None ) -> Any:
	"""Get chat module.

	Purpose:
	    Returns normalized information for the application component. The method provides a stable
	    view of provider capabilities, stored state, or response metadata so UI controls and
	    downstream
	    logic can consume it consistently.

	Args:
	    provider (Optional[str]): Provider value used by the operation.

	Returns:
	    Any: Return value produced by the operation."""
	return get_provider_instance( 'Chat', provider )

get_tts_module

get_tts_module(provider: Optional[str] = None) -> Any

Get tts module.

Purpose

Returns normalized information for the application component. The method provides a stable view of provider capabilities, stored state, or response metadata so UI controls and downstream logic can consume it consistently.

Parameters:

Name Type Description Default
provider Optional[str]

Provider value used by the operation.

None

Returns:

Name Type Description
Any Any

Return value produced by the operation.

Source code in app.py
def get_tts_module( provider: Optional[ str ] = None ) -> Any:
	"""Get tts module.

	Purpose:
	    Returns normalized information for the application component. The method provides a stable
	    view of provider capabilities, stored state, or response metadata so UI controls and
	    downstream
	    logic can consume it consistently.

	Args:
	    provider (Optional[str]): Provider value used by the operation.

	Returns:
	    Any: Return value produced by the operation."""
	return get_provider_instance( 'TTS', provider )

get_images_module

get_images_module(provider: Optional[str] = None) -> Any

Get images module.

Purpose

Returns normalized information for the application component. The method provides a stable view of provider capabilities, stored state, or response metadata so UI controls and downstream logic can consume it consistently.

Parameters:

Name Type Description Default
provider Optional[str]

Provider value used by the operation.

None

Returns:

Name Type Description
Any Any

Return value produced by the operation.

Source code in app.py
def get_images_module( provider: Optional[ str ] = None ) -> Any:
	"""Get images module.

	Purpose:
	    Returns normalized information for the application component. The method provides a stable
	    view of provider capabilities, stored state, or response metadata so UI controls and
	    downstream
	    logic can consume it consistently.

	Args:
	    provider (Optional[str]): Provider value used by the operation.

	Returns:
	    Any: Return value produced by the operation."""
	return get_provider_instance( 'Images', provider )

get_embeddings_module

get_embeddings_module(
    provider: Optional[str] = None,
) -> Any

Get embeddings module.

Purpose

Returns normalized information for the application component. The method provides a stable view of provider capabilities, stored state, or response metadata so UI controls and downstream logic can consume it consistently.

Parameters:

Name Type Description Default
provider Optional[str]

Provider value used by the operation.

None

Returns:

Name Type Description
Any Any

Return value produced by the operation.

Source code in app.py
def get_embeddings_module( provider: Optional[ str ] = None ) -> Any:
	"""Get embeddings module.

	Purpose:
	    Returns normalized information for the application component. The method provides a stable
	    view of provider capabilities, stored state, or response metadata so UI controls and
	    downstream
	    logic can consume it consistently.

	Args:
	    provider (Optional[str]): Provider value used by the operation.

	Returns:
	    Any: Return value produced by the operation."""
	return get_provider_instance( 'Embeddings', provider )

get_translation_module

get_translation_module(
    provider: Optional[str] = None,
) -> Any

Get translation module.

Purpose

Returns normalized information for the application component. The method provides a stable view of provider capabilities, stored state, or response metadata so UI controls and downstream logic can consume it consistently.

Parameters:

Name Type Description Default
provider Optional[str]

Provider value used by the operation.

None

Returns:

Name Type Description
Any Any

Return value produced by the operation.

Source code in app.py
def get_translation_module( provider: Optional[ str ] = None ) -> Any:
	"""Get translation module.

	Purpose:
	    Returns normalized information for the application component. The method provides a stable
	    view of provider capabilities, stored state, or response metadata so UI controls and
	    downstream
	    logic can consume it consistently.

	Args:
	    provider (Optional[str]): Provider value used by the operation.

	Returns:
	    Any: Return value produced by the operation."""
	return get_provider_instance( 'Translation', provider )

get_transcription_module

get_transcription_module(
    provider: Optional[str] = None,
) -> Any

Get transcription module.

Purpose

Returns normalized information for the application component. The method provides a stable view of provider capabilities, stored state, or response metadata so UI controls and downstream logic can consume it consistently.

Parameters:

Name Type Description Default
provider Optional[str]

Provider value used by the operation.

None

Returns:

Name Type Description
Any Any

Return value produced by the operation.

Source code in app.py
def get_transcription_module( provider: Optional[ str ] = None ) -> Any:
	"""Get transcription module.

	Purpose:
	    Returns normalized information for the application component. The method provides a stable
	    view of provider capabilities, stored state, or response metadata so UI controls and
	    downstream
	    logic can consume it consistently.

	Args:
	    provider (Optional[str]): Provider value used by the operation.

	Returns:
	    Any: Return value produced by the operation."""
	return get_provider_instance( 'Transcription', provider )

get_files_module

get_files_module(provider: Optional[str] = None) -> Any

Get files module.

Purpose

Returns normalized information for the application component. The method provides a stable view of provider capabilities, stored state, or response metadata so UI controls and downstream logic can consume it consistently.

Parameters:

Name Type Description Default
provider Optional[str]

Provider value used by the operation.

None

Returns:

Name Type Description
Any Any

Return value produced by the operation.

Source code in app.py
def get_files_module( provider: Optional[ str ] = None ) -> Any:
	"""Get files module.

	Purpose:
	    Returns normalized information for the application component. The method provides a stable
	    view of provider capabilities, stored state, or response metadata so UI controls and
	    downstream
	    logic can consume it consistently.

	Args:
	    provider (Optional[str]): Provider value used by the operation.

	Returns:
	    Any: Return value produced by the operation."""
	return get_provider_instance( 'Files', provider )

get_vectorstores_module

get_vectorstores_module(
    provider: Optional[str] = None,
) -> Any

Get vector stores module.

Purpose

Returns the OpenAI VectorStores wrapper used by the Vector Stores mode. The function prevents provider-specific retrieval resources from being routed through the OpenAI VectorStores contract.

Parameters:

Name Type Description Default
provider Optional[str]

Provider selected by the application.

None

Returns:

Name Type Description
Any Any

Instantiated OpenAI VectorStores wrapper.

Source code in app.py
def get_vectorstores_module( provider: Optional[ str ] = None ) -> Any:
	"""Get vector stores module.

	Purpose:
	    Returns the OpenAI VectorStores wrapper used by the Vector Stores mode. The function
	    prevents provider-specific retrieval resources from being routed through the OpenAI
	    VectorStores contract.

	Args:
	    provider (Optional[str]): Provider selected by the application.

	Returns:
	    Any: Instantiated OpenAI VectorStores wrapper.
	"""
	selected_provider = get_provider_name( provider )

	if selected_provider != 'GPT':
		raise ValueError(
			f'Provider "{selected_provider}" does not provide OpenAI Vector Stores.' )

	return get_provider_instance( 'VectorStores', selected_provider )

get_collections_module

get_collections_module(
    provider: Optional[str] = None,
) -> Any

Get collections module.

Purpose

Returns the xAI Collections wrapper used by the Collections mode. The function keeps Grok Collections separate from OpenAI Vector Stores and Gemini File Search Stores.

Parameters:

Name Type Description Default
provider Optional[str]

Provider selected by the application.

None

Returns:

Name Type Description
Any Any

Instantiated xAI Collections wrapper.

Source code in app.py
def get_collections_module( provider: Optional[ str ] = None ) -> Any:
	"""Get collections module.

	Purpose:
	    Returns the xAI Collections wrapper used by the Collections mode. The function keeps
	    Grok Collections separate from OpenAI Vector Stores and Gemini File Search Stores.

	Args:
	    provider (Optional[str]): Provider selected by the application.

	Returns:
	    Any: Instantiated xAI Collections wrapper.
	"""
	selected_provider = get_provider_name( provider )

	if selected_provider != 'Grok':
		raise ValueError(
			f'Provider "{selected_provider}" does not provide xAI Collections.' )

	return get_provider_instance( 'Collections', selected_provider )

get_file_search_module

get_file_search_module(
    provider: Optional[str] = None,
) -> Any

Get file search module.

Purpose

Returns the Gemini FileSearch wrapper used by the File Search Stores mode. The function prevents OpenAI Vector Stores and xAI Collections from being routed through the Gemini File Search contract.

Parameters:

Name Type Description Default
provider Optional[str]

Provider selected by the application.

None

Returns:

Name Type Description
Any Any

Instantiated Gemini FileSearch wrapper.

Source code in app.py
def get_file_search_module( provider: Optional[ str ] = None ) -> Any:
	"""Get file search module.

	Purpose:
	    Returns the Gemini FileSearch wrapper used by the File Search Stores mode. The function
	    prevents OpenAI Vector Stores and xAI Collections from being routed through the Gemini
	    File Search contract.

	Args:
	    provider (Optional[str]): Provider selected by the application.

	Returns:
	    Any: Instantiated Gemini FileSearch wrapper.
	"""
	selected_provider = get_provider_name( provider )

	if selected_provider != 'Gemini':
		raise ValueError(
			f'Provider "{selected_provider}" does not provide Gemini File Search Stores.' )

	return get_provider_instance( 'FileSearch', selected_provider )

get_cloud_buckets_module

get_cloud_buckets_module(
    provider: Optional[str] = None,
) -> Any

Get cloud buckets module.

Purpose

Returns normalized information for the application component. The method provides a stable view of provider capabilities, stored state, or response metadata so UI controls and downstream logic can consume it consistently.

Parameters:

Name Type Description Default
provider Optional[str]

Provider value used by the operation.

None

Returns:

Name Type Description
Any Any

Return value produced by the operation.

Source code in app.py
def get_cloud_buckets_module( provider: Optional[ str ] = None ) -> Any:
	"""Get cloud buckets module.

	Purpose:
	    Returns normalized information for the application component. The method provides a stable
	    view of provider capabilities, stored state, or response metadata so UI controls and
	    downstream
	    logic can consume it consistently.

	Args:
	    provider (Optional[str]): Provider value used by the operation.

	Returns:
	    Any: Return value produced by the operation."""
	return get_provider_instance( 'CloudBuckets', provider )

get_mode_classes

get_mode_classes(
    mode: Optional[str] = None,
    provider: Optional[str] = None,
) -> List[str]

Get mode classes.

Purpose

Returns normalized information for the application component. The method provides a stable view of provider capabilities, stored state, or response metadata so UI controls and downstream logic can consume it consistently.

Parameters:

Name Type Description Default
mode Optional[str]

Mode value used by the operation.

None
provider Optional[str]

Provider value used by the operation.

None

Returns:

Type Description
List[str]

List[str]: Return value produced by the operation.

Source code in app.py
def get_mode_classes( mode: Optional[ str ] = None,
	provider: Optional[ str ] = None ) -> List[ str ]:
	"""Get mode classes.

	Purpose:
	    Returns normalized information for the application component. The method provides a stable
	    view of provider capabilities, stored state, or response metadata so UI controls and
	    downstream
	    logic can consume it consistently.

	Args:
	    mode (Optional[str]): Mode value used by the operation.
	    provider (Optional[str]): Provider value used by the operation.

	Returns:
	    List[str]: Return value produced by the operation."""
	selected_mode = mode or st.session_state.get( 'mode', 'Text' )
	selected_provider = get_provider_name( provider )
	provider_class_map = getattr( cfg, 'PROVIDER_CLASS_MAP', None )

	if isinstance( provider_class_map, dict ):
		provider_modes = provider_class_map.get( selected_provider, { } )
		mapped = provider_modes.get( selected_mode, [ ] )

		if isinstance( mapped, str ):
			return [ mapped ]

		if isinstance( mapped, list ):
			return mapped

	mode_class_map = getattr( cfg, 'MODE_CLASS_MAP', { } )
	mapped = mode_class_map.get( selected_mode, [ ] )

	if isinstance( mapped, str ):
		return [ mapped ]

	if isinstance( mapped, list ):
		return mapped

	return [ ]

provider_supports_mode

provider_supports_mode(
    provider: str, mode_name: str
) -> bool

Determine provider mode support.

Purpose

Determines whether the selected provider exposes the wrapper and functionality required by an application mode. The function preserves Buddy's Chat alias while enforcing provider-native retrieval-resource boundaries for OpenAI Vector Stores, xAI Collections, Gemini File Search Stores, and Google Cloud Buckets.

Parameters:

Name Type Description Default
provider str

Required provider name.

required
mode_name str

Required application mode name.

required

Returns:

Name Type Description
bool bool

True when the provider supports the requested mode; otherwise False.

Source code in app.py
def provider_supports_mode( provider: str, mode_name: str ) -> bool:
	"""Determine provider mode support.

	Purpose:
	    Determines whether the selected provider exposes the wrapper and functionality required
	    by an application mode. The function preserves Buddy's Chat alias while enforcing
	    provider-native retrieval-resource boundaries for OpenAI Vector Stores, xAI Collections,
	    Gemini File Search Stores, and Google Cloud Buckets.

	Args:
	    provider (str): Required provider name.
	    mode_name (str): Required application mode name.

	Returns:
	    bool: True when the provider supports the requested mode; otherwise False.
	"""
	throw_if( 'provider', provider )
	throw_if( 'mode_name', mode_name )

	selected_provider = provider
	selected_mode = normalize_mode_name( mode_name )

	# ------------------------------------------------------------------
	# Application Modes Without Provider Wrappers
	# ------------------------------------------------------------------
	if selected_mode in [ 'Prompt Engineering', 'Data Management', 'Export', ]:
		return True

	# ------------------------------------------------------------------
	# Buddy Chat Alias
	# ------------------------------------------------------------------
	if selected_mode == 'Chat':
		if selected_provider == 'GPT':
			return provider_has_class( 'Text', selected_provider )

		return provider_has_class( 'Chat', selected_provider )

	# ------------------------------------------------------------------
	# Shared Provider Workflows
	# ------------------------------------------------------------------
	if selected_mode == 'Text':
		if selected_provider == 'GPT':
			return provider_has_class( 'Text', selected_provider )

		return provider_has_class( 'Chat', selected_provider )

	if selected_mode == 'Images':
		return provider_has_class( 'Images', selected_provider )

	if selected_mode == 'Audio':
		return provider_has_class( 'Audio', selected_provider )

	if selected_mode == 'Embeddings':
		return provider_has_class( 'Embeddings', selected_provider )

	if selected_mode == 'Document Q&A':
		return provider_has_class( 'DocumentQnA', selected_provider )

	if selected_mode == 'Files':
		return provider_has_class( 'Files', selected_provider )

	# ------------------------------------------------------------------
	# Provider-Native Retrieval Resources
	# ------------------------------------------------------------------
	if selected_mode == 'Vector Stores':
		return (selected_provider == 'GPT' and provider_has_class( 'VectorStores',
			selected_provider ))

	if selected_mode == 'Collections':
		return (selected_provider == 'Grok' and provider_has_class( 'Collections',
			selected_provider ))

	if selected_mode == 'File Search Stores':
		return (selected_provider == 'Gemini' and provider_has_class( 'FileSearch',
			selected_provider ))

	if selected_mode == 'Google Cloud Buckets':
		return (selected_provider == 'Gemini' and provider_has_class( 'CloudBuckets',
			selected_provider ))

	return False

require_provider_mode

require_provider_mode(
    mode: Optional[str] = None,
    provider: Optional[str] = None,
) -> bool

Require provider mode.

Purpose

Performs the require_provider_mode workflow using the inputs supplied by the caller and the current runtime configuration. The function keeps this behavior isolated so related UI, provider, and data-processing paths can call it consistently.

Parameters:

Name Type Description Default
mode Optional[str]

Mode value used by the operation.

None
provider Optional[str]

Provider value used by the operation.

None

Returns:

Name Type Description
bool bool

Return value produced by the operation.

Source code in app.py
def require_provider_mode( mode: Optional[ str ] = None, provider: Optional[ str ] = None ) -> bool:
	"""Require provider mode.

	Purpose:
	    Performs the require_provider_mode workflow using the inputs supplied by the caller and the
	    current runtime configuration. The function keeps this behavior isolated so related UI,
	    provider, and data-processing paths can call it consistently.

	Args:
	    mode (Optional[str]): Mode value used by the operation.
	    provider (Optional[str]): Provider value used by the operation.

	Returns:
	    bool: Return value produced by the operation."""
	selected_mode = mode or st.session_state.get( 'mode', 'Text' )
	selected_provider = get_provider_name( provider )
	classes = get_mode_classes( selected_mode, selected_provider )
	missing = [ class_name for class_name in classes if
		not provider_has_class( class_name, selected_provider ) ]

	if missing:
		st.warning( f'{selected_provider} does not currently expose the required wrapper(s) for '
		            f'{selected_mode}: {", ".join( missing )}.' )
		return False

	return True

get_provider_options

get_provider_options() -> List[str]

Get provider options.

Purpose

Returns normalized information for the application component. The method provides a stable view of provider capabilities, stored state, or response metadata so UI controls and downstream logic can consume it consistently.

Returns:

Type Description
List[str]

List[str]: Return value produced by the operation.

Source code in app.py
def get_provider_options( ) -> List[ str ]:
	"""Get provider options.

	Purpose:
	    Returns normalized information for the application component. The method provides a stable
	    view of provider capabilities, stored state, or response metadata so UI controls and
	    downstream
		logic can consume it consistently.

	Returns:
	    List[str]: Return value produced by the operation."""
	providers = getattr( cfg, 'PROVIDERS', { 'GPT': 'gpt', 'Gemini': 'gemini', 'Grok': 'grok' } )
	return list( providers.keys( ) )

get_raw_provider_modes

get_raw_provider_modes(provider: str) -> List[str]

Get raw provider modes.

Purpose

Returns the application modes configured for the selected provider while enforcing provider-native retrieval-resource terminology. GPT retains Vector Stores, Gemini retains File Search Stores and Google Cloud Buckets, and Grok exposes Collections instead of Vector Stores.

Parameters:

Name Type Description Default
provider str

Required provider name.

required

Returns:

Type Description
List[str]

List[str]: Ordered provider-specific application modes.

Source code in app.py
def get_raw_provider_modes( provider: str ) -> List[ str ]:
	"""Get raw provider modes.

	Purpose:
	    Returns the application modes configured for the selected provider while enforcing
	    provider-native retrieval-resource terminology. GPT retains Vector Stores, Gemini retains
	    File Search Stores and Google Cloud Buckets, and Grok exposes Collections instead of
	    Vector Stores.

	Args:
	    provider (str): Required provider name.

	Returns:
	    List[str]: Ordered provider-specific application modes.
	"""
	throw_if( 'provider', provider )
	selected_provider = provider
	class_mode_map = getattr( cfg, 'CLASS_MODE_MAP', None )
	raw_modes: List[ str ] = [ ]

	if isinstance( class_mode_map, dict ) and selected_provider in class_mode_map:
		configured_modes = class_mode_map.get( selected_provider, [ ] )
		raw_modes = list( configured_modes or [ ] )
	elif selected_provider == 'Gemini':
		raw_modes = list( getattr( cfg, 'GEMINI_MODES', [ ] ) )
	elif selected_provider == 'Grok':
		raw_modes = list( getattr( cfg, 'GROK_MODES', [ ] ) )
	else:
		raw_modes = list( getattr( cfg, 'GPT_MODES', [ ] ) )

	provider_modes: List[ str ] = [ ]

	for configured_mode in raw_modes:
		mode_name = str( configured_mode ).strip( )

		if not mode_name:
			continue

		# Grok uses Collections rather than OpenAI Vector Stores.
		if selected_provider == 'Grok' and mode_name == 'Vector Stores':
			mode_name = 'Collections'

		# Vector Stores are specific to the OpenAI provider workflow.
		if selected_provider != 'GPT' and mode_name == 'Vector Stores':
			continue

		# Collections are specific to the xAI provider workflow.
		if selected_provider != 'Grok' and mode_name == 'Collections':
			continue

		# Gemini retrieval resources remain separate provider-native modes.
		if selected_provider != 'Gemini' and mode_name in [ 'File Search Stores',
			'Google Cloud Buckets', ]:
			continue

		if mode_name not in provider_modes:
			provider_modes.append( mode_name )

	return provider_modes

normalize_mode_name

normalize_mode_name(mode_name: Optional[str]) -> str

Normalize mode name.

Purpose

Normalizes incoming values into a predictable representation for application processing. The function reduces provider, user-input, or serialization differences before values are stored or displayed.

Parameters:

Name Type Description Default
mode_name Optional[str]

Mode name value used by the operation.

required

Returns:

Name Type Description
str str

Return value produced by the operation.

Source code in app.py
def normalize_mode_name( mode_name: Optional[ str ] ) -> str:
	"""Normalize mode name.

	Purpose:
	    Normalizes incoming values into a predictable representation for application processing.
	    The function reduces provider, user-input, or serialization differences before values are
	    stored or displayed.

	Args:
	    mode_name (Optional[str]): Mode name value used by the operation.

	Returns:
	    str: Return value produced by the operation."""
	if not mode_name:
		return 'Text'

	mode_aliases = { 'Embedding': 'Embeddings', 'Documents': 'Document Q&A',
		'Data Export': 'Export', 'Export Data': 'Export', }

	return mode_aliases.get( mode_name, mode_name )

normalize_mode_list

normalize_mode_list(modes: List[str]) -> List[str]

Normalize mode list.

Purpose

Normalizes incoming values into a predictable representation for application processing. The function reduces provider, user-input, or serialization differences before values are stored or displayed.

Parameters:

Name Type Description Default
modes List[str]

Modes value used by the operation.

required

Returns:

Type Description
List[str]

List[str]: Return value produced by the operation.

Source code in app.py
def normalize_mode_list( modes: List[ str ] ) -> List[ str ]:
	"""Normalize mode list.

	Purpose:
	    Normalizes incoming values into a predictable representation for application processing.
	    The function reduces provider, user-input, or serialization differences before values are
	    stored or displayed.

	Args:
	    modes (List[str]): Modes value used by the operation.

	Returns:
	    List[str]: Return value produced by the operation."""
	normalized = [ ]

	for item in modes:
		mode_name = normalize_mode_name( item )
		if mode_name not in normalized:
			normalized.append( mode_name )

	return normalized

mode_requires_runtime_wrapper

mode_requires_runtime_wrapper(mode_name: str) -> bool

Mode requires runtime wrapper.

Purpose

Performs the mode_requires_runtime_wrapper workflow using the inputs supplied by the caller and the current runtime configuration. The function keeps this behavior isolated so related UI, provider, and data-processing paths can call it consistently.

Parameters:

Name Type Description Default
mode_name str

Mode name value used by the operation.

required

Returns:

Name Type Description
bool bool

Return value produced by the operation.

Source code in app.py
def mode_requires_runtime_wrapper( mode_name: str ) -> bool:
	"""Mode requires runtime wrapper.

	Purpose:
	    Performs the mode_requires_runtime_wrapper workflow using the inputs supplied by the
	    caller and the current runtime configuration. The function keeps this behavior isolated so
	    related UI,
	    provider, and data-processing paths can call it consistently.

	Args:
	    mode_name (str): Mode name value used by the operation.

	Returns:
	    bool: Return value produced by the operation."""
	non_wrapper_modes = [ 'Prompt Engineering', 'Data Management', 'Export', ]

	return mode_name not in non_wrapper_modes

get_supported_provider_modes

get_supported_provider_modes(provider: str) -> List[str]

Get supported provider modes.

Purpose

Returns the configured application modes available to the selected provider. Mode availability is determined by the provider-specific configuration and is not altered by runtime wrapper introspection.

Parameters:

Name Type Description Default
provider str

Selected provider name.

required

Returns:

Type Description
List[str]

List[str]: Normalized provider modes in configured display order.

Source code in app.py
def get_supported_provider_modes( provider: str ) -> List[ str ]:
	"""Get supported provider modes.

	Purpose:
	    Returns the configured application modes available to the selected provider. Mode
	    availability is determined by the provider-specific configuration and is not altered by
	    runtime wrapper introspection.

	Args:
	    provider (str): Selected provider name.

	Returns:
	    List[str]: Normalized provider modes in configured display order.
	"""
	raw_modes = get_raw_provider_modes( provider )
	modes = normalize_mode_list( raw_modes )

	if not modes:
		return [ 'Text' ]

	return modes

get_mode_index

get_mode_index(
    modes: List[str], current_mode: Optional[str]
) -> int

Get mode index.

Purpose

Returns normalized information for the application component. The method provides a stable view of provider capabilities, stored state, or response metadata so UI controls and downstream logic can consume it consistently.

Parameters:

Name Type Description Default
modes List[str]

Modes value used by the operation.

required
current_mode Optional[str]

Current mode value used by the operation.

required

Returns:

Name Type Description
int int

Return value produced by the operation.

Source code in app.py
def get_mode_index( modes: List[ str ], current_mode: Optional[ str ] ) -> int:
	"""Get mode index.

	Purpose:
	    Returns normalized information for the application component. The method provides a stable
	    view of provider capabilities, stored state, or response metadata so UI controls and
	    downstream
	    logic can consume it consistently.

	Args:
	    modes (List[str]): Modes value used by the operation.
	    current_mode (Optional[str]): Current mode value used by the operation.

	Returns:
	    int: Return value produced by the operation."""
	mode_name = normalize_mode_name( current_mode )

	if mode_name in modes:
		return modes.index( mode_name )

	return 0

render_provider_keys

render_provider_keys() -> None

Render provider keys.

Purpose

Renders the requested user interface element or result block in Streamlit using normalized inputs. The function keeps presentation logic isolated from provider calls and data-processing steps so the screen output remains predictable.

Returns:

Name Type Description
None None

This function performs its work through side effects and does not return a value.

Source code in app.py
def render_provider_keys( ) -> None:
	"""Render provider keys.

	Purpose:
	    Renders the requested user interface element or result block in Streamlit using normalized
	    inputs. The function keeps presentation logic isolated from provider calls and
	    data-processing steps so the screen output remains predictable.

	Returns:
	    None: This function performs its work through side effects and does not return a value."""
	with st.expander( 'Keys:', expanded=False ):
		openai_key = st.text_input( 'OpenAI API Key', type='password',
			value=get_runtime_config_value( 'openai_api_key', 'OPENAI_API_KEY', 'OPENAI_API_KEY' ),
			help='Overrides OPENAI_API_KEY from config.py for this session only.',
			key='sidebar_openai_api_key' )

		gemini_key = st.text_input( 'Gemini API Key', type='password',
			value=get_runtime_config_value( 'gemini_api_key', 'GEMINI_API_KEY', 'GEMINI_API_KEY' ),
			help='Overrides GEMINI_API_KEY from config.py for this session only.',
			key='sidebar_gemini_api_key' )

		xai_key = st.text_input( 'xAI API Key', type='password',
			value=get_runtime_config_value( 'xai_api_key', 'XAI_API_KEY', 'XAI_API_KEY' ),
			help='Overrides XAI_API_KEY from config.py for this session only.',
			key='sidebar_xai_api_key' )

		google_key = st.text_input( 'Google API Key', type='password',
			value=get_runtime_config_value( 'google_api_key', 'GOOGLE_API_KEY', 'GOOGLE_API_KEY' ),
			help='Overrides GOOGLE_API_KEY from config.py for this session only.',
			key='sidebar_google_api_key' )

		google_cse_id = st.text_input( 'Google CSE ID', type='password',
			value=get_runtime_config_value( 'google_cse_id', 'GOOGLE_CSE_ID', 'GOOGLE_CSE_ID' ),
			help='Overrides GOOGLE_CSE_ID from config.py for this session only.',
			key='sidebar_google_cse_id' )

		google_cloud_project_id = st.text_input( 'Google Cloud Project ID', type='password',
			value=get_runtime_config_value( 'google_cloud_project_id', 'GOOGLE_CLOUD_PROJECT_ID',
				'GOOGLE_CLOUD_PROJECT_ID' ),
			help='Overrides GOOGLE_CLOUD_PROJECT_ID from config.py for this session only.',
			key='sidebar_google_cloud_project_id' )

		google_cloud_location = st.text_input( 'Google Cloud Location', type='password',
			value=get_runtime_config_value( 'google_cloud_location', 'GOOGLE_CLOUD_LOCATION',
				'GOOGLE_CLOUD_LOCATION' ),
			help='Overrides GOOGLE_CLOUD_LOCATION from config.py for this session only.',
			key='sidebar_google_cloud_location' )

		sync_provider_config( 'openai_api_key', 'OPENAI_API_KEY', 'OPENAI_API_KEY', openai_key,
			'GPT' )
		sync_provider_config( 'gemini_api_key', 'GEMINI_API_KEY', 'GEMINI_API_KEY', gemini_key,
			'Gemini' )
		sync_provider_config( 'xai_api_key', 'XAI_API_KEY', 'XAI_API_KEY', xai_key, 'Grok' )
		sync_provider_config( 'google_api_key', 'GOOGLE_API_KEY', 'GOOGLE_API_KEY', google_key )
		sync_provider_config( 'google_cse_id', 'GOOGLE_CSE_ID', 'GOOGLE_CSE_ID', google_cse_id )
		sync_provider_config( 'google_cloud_project_id', 'GOOGLE_CLOUD_PROJECT_ID',
			'GOOGLE_CLOUD_PROJECT_ID', google_cloud_project_id )
		sync_provider_config( 'google_cloud_location', 'GOOGLE_CLOUD_LOCATION',
			'GOOGLE_CLOUD_LOCATION', google_cloud_location )

get_text_options

get_text_options(
    instance: Any,
    attr_name: str,
    fallback: Optional[List[str]] = None,
) -> List[str]

Get text options.

Purpose

Returns normalized option values exposed by the selected provider wrapper.

Parameters:

Name Type Description Default
instance Any

Provider wrapper instance.

required
attr_name str

Option-property name.

required
fallback Optional[List[str]]

Values returned when the property is unavailable.

None

Returns:

Type Description
List[str]

List[str]: Normalized provider option values.

Source code in app.py
def get_text_options( instance: Any, attr_name: str,
	fallback: Optional[ List[ str ] ] = None ) -> List[ str ]:
	"""Get text options.

	Purpose:
		Returns normalized option values exposed by the selected provider wrapper.

	Args:
		instance (Any): Provider wrapper instance.
		attr_name (str): Option-property name.
		fallback (Optional[List[str]]): Values returned when the property is unavailable.

	Returns:
		List[str]: Normalized provider option values.
	"""
	values = getattr( instance, attr_name, None )

	if callable( values ):
		values = values( )

	if values is None:
		values = fallback or [ ]

	if isinstance( values, tuple ):
		values = list( values )

	if not isinstance( values, list ):
		return fallback or [ ]

	return [ str( value ) for value in values if str( value ).strip( ) ]

parse_semicolon_list

parse_semicolon_list(value: Any) -> List[str]

Parse semicolon list.

Purpose

Converts a semicolon-delimited value into normalized non-empty entries.

Parameters:

Name Type Description Default
value Any

Delimited source value.

required

Returns:

Type Description
List[str]

List[str]: Parsed values.

Source code in app.py
def parse_semicolon_list( value: Any ) -> List[ str ]:
	"""Parse semicolon list.

	Purpose:
		Converts a semicolon-delimited value into normalized non-empty entries.

	Args:
		value (Any): Delimited source value.

	Returns:
		List[str]: Parsed values.
	"""
	return [ item.strip( ) for item in str( value or '' ).split( ';' ) if item.strip( ) ]

parse_comma_list

parse_comma_list(value: Any) -> List[str]

Parse comma list.

Purpose

Converts a comma-delimited value into normalized non-empty entries.

Parameters:

Name Type Description Default
value Any

Delimited source value.

required

Returns:

Type Description
List[str]

List[str]: Parsed values.

Source code in app.py
def parse_comma_list( value: Any ) -> List[ str ]:
	"""Parse comma list.

	Purpose:
		Converts a comma-delimited value into normalized non-empty entries.

	Args:
		value (Any): Delimited source value.

	Returns:
		List[str]: Parsed values.
	"""
	return [ item.strip( ) for item in str( value or '' ).split( ',' ) if item.strip( ) ]

get_grok_collection_options

get_grok_collection_options() -> Dict[str, str]

Get Grok collection options.

Purpose

Returns configured xAI Collection labels mapped to provider collection identifiers.

Returns:

Type Description
Dict[str, str]

Dict[str, str]: Collection labels mapped to identifiers.

Source code in app.py
def get_grok_collection_options( ) -> Dict[ str, str ]:
	"""Get Grok collection options.

	Purpose:
		Returns configured xAI Collection labels mapped to provider collection identifiers.

	Returns:
		Dict[str, str]: Collection labels mapped to identifiers.
	"""
	configured_collections = getattr( cfg, 'GROK_COLLECTIONS', { }, )
	collections: Dict[ str, str ] = { }

	if isinstance( configured_collections, dict ):
		for label, collection_id in configured_collections.items( ):
			if str( label ).strip( ) and str( collection_id ).strip( ):
				collections[ str( label ) ] = str( collection_id )

		return collections

	if isinstance( configured_collections, list ):
		for row in configured_collections:
			if not isinstance( row, dict ):
				continue

			for label, collection_id in row.items( ):
				if str( label ).strip( ) and str( collection_id ).strip( ):
					collections[ str( label ) ] = str( collection_id )

	return collections

get_selected_grok_collection_ids

get_selected_grok_collection_ids() -> List[str]

Get selected Grok collection IDs.

Purpose

Resolves configured collection labels and manually entered collection identifiers.

Returns:

Type Description
List[str]

List[str]: Unique xAI Collection identifiers.

Source code in app.py
def get_selected_grok_collection_ids( ) -> List[ str ]:
	"""Get selected Grok collection IDs.

	Purpose:
		Resolves configured collection labels and manually entered collection identifiers.

	Returns:
		List[str]: Unique xAI Collection identifiers.
	"""
	collection_map = get_grok_collection_options( )
	selected_labels = st.session_state.get( 'text_grok_collection_labels', [ ], )
	manual_ids = parse_comma_list(
		st.session_state.get( 'text_grok_collection_ids_input', '', ) )
	resolved_ids: List[ str ] = [ ]

	for label in selected_labels:
		collection_id = collection_map.get( str( label ), '', )

		if collection_id and collection_id not in resolved_ids:
			resolved_ids.append( collection_id )

	for collection_id in manual_ids:
		if collection_id not in resolved_ids:
			resolved_ids.append( collection_id )

	st.session_state[ 'text_grok_collection_ids' ] = resolved_ids
	return resolved_ids

sanitize_text_selection

sanitize_text_selection(
    key: str, valid_options: List[str], default: Any = ""
) -> None

Sanitize text selection.

Purpose

Removes a stale single-select value when it is not supported by the selected provider.

Parameters:

Name Type Description Default
key str

Session-state key.

required
valid_options List[str]

Supported option values.

required
default Any

Replacement value.

''

Returns:

Name Type Description
None None

This function updates session state.

Source code in app.py
def sanitize_text_selection( key: str, valid_options: List[ str ], default: Any = '' ) -> None:
	"""Sanitize text selection.

	Purpose:
		Removes a stale single-select value when it is not supported by the selected
		provider.

	Args:
		key (str): Session-state key.
		valid_options (List[str]): Supported option values.
		default (Any): Replacement value.

	Returns:
		None: This function updates session state.
	"""
	current_value = st.session_state.get( key, default, )

	if current_value in [ None, '', ]:
		return

	if valid_options and current_value not in valid_options:
		st.session_state[ key ] = default

sanitize_text_multiselect

sanitize_text_multiselect(
    key: str, valid_options: List[str]
) -> None

Sanitize text multiselect.

Purpose

Removes stale multi-select values that are unsupported by the selected provider.

Parameters:

Name Type Description Default
key str

Session-state key.

required
valid_options List[str]

Supported option values.

required

Returns:

Name Type Description
None None

This function updates session state.

Source code in app.py
def sanitize_text_multiselect( key: str, valid_options: List[ str ] ) -> None:
	"""Sanitize text multiselect.

	Purpose:
		Removes stale multi-select values that are unsupported by the selected provider.

	Args:
		key (str): Session-state key.
		valid_options (List[str]): Supported option values.

	Returns:
		None: This function updates session state.
	"""
	current_values = st.session_state.get( key, [ ], )

	if not isinstance( current_values, list ):
		st.session_state[ key ] = [ ]
		return

	st.session_state[ key ] = [ value for value in current_values if value in valid_options ]

build_text_context

build_text_context() -> List[Dict[str, str]]

Build text context.

Purpose

Returns prior Text Mode user and assistant messages without including the current prompt.

Returns:

Type Description
List[Dict[str, str]]

List[Dict[str, str]]: Prior conversation messages.

Source code in app.py
def build_text_context( ) -> List[ Dict[ str, str ] ]:
	"""Build text context.

	Purpose:
		Returns prior Text Mode user and assistant messages without including the current
		prompt.

	Returns:
		List[Dict[str, str]]: Prior conversation messages.
	"""
	if st.session_state.get( 'text_input', 'conversation' ) != 'conversation':
		return [ ]

	messages = st.session_state.get( 'text_messages', [ ], )

	if not isinstance( messages, list ):
		return [ ]

	return [ { 'role': str( message.get( 'role', '', ) ),
		'content': str( message.get( 'content', '', ) ), } for message in messages if
		isinstance( message, dict ) and message.get( 'role' ) in [ 'user',
			'assistant', ] and str( message.get( 'content', '', ) ).strip( ) ]

normalize_text_domains

normalize_text_domains() -> List[str]

Normalize allowed domains.

Purpose

Removes URL schemes and paths from Web Search domain restrictions.

Returns:

Type Description
List[str]

List[str]: Provider-compatible domain names.

Source code in app.py
def normalize_text_domains( ) -> List[ str ]:
	"""Normalize allowed domains.

	Purpose:
		Removes URL schemes and paths from Web Search domain restrictions.

	Returns:
		List[str]: Provider-compatible domain names.
	"""
	domains: List[ str ] = [ ]

	for entered_domain in parse_comma_list( st.session_state.get( 'text_domains_input', '',
	) ):
		domain = entered_domain.strip( )

		if domain.startswith( 'https://' ):
			domain = domain[ len( 'https://' ): ]
		elif domain.startswith( 'http://' ):
			domain = domain[ len( 'http://' ): ]

		domain = domain.split( '/', 1, )[ 0 ].strip( )

		if domain and domain not in domains:
			domains.append( domain )

	return domains

get_text_response_schema

get_text_response_schema(
    required: bool = False,
) -> Optional[Dict[str, Any]]

Get text response schema.

Purpose

Parses the configured JSON schema only when the selected response mode requires it.

Parameters:

Name Type Description Default
required bool

Indicates whether an empty schema is invalid.

False

Returns:

Type Description
Optional[Dict[str, Any]]

Optional[Dict[str, Any]]: Parsed JSON schema or None.

Raises:

Type Description
ValueError

Raised when required schema text is missing or invalid.

Source code in app.py
def get_text_response_schema( required: bool = False ) -> Optional[ Dict[ str, Any ] ]:
	"""Get text response schema.

	Purpose:
		Parses the configured JSON schema only when the selected response mode requires it.

	Args:
		required (bool): Indicates whether an empty schema is invalid.

	Returns:
		Optional[Dict[str, Any]]: Parsed JSON schema or None.

	Raises:
		ValueError: Raised when required schema text is missing or invalid.
	"""
	schema_text = str( st.session_state.get( 'text_json_schema', '', ) or '' ).strip( )

	if not schema_text:
		if required:
			raise ValueError( 'Response Schema is required when JSON Schema is selected.' )

		return None

	response_schema = json.loads( schema_text )
	if not isinstance( response_schema, dict ):
		raise ValueError( 'Response Schema must contain a JSON object.' )

	return response_schema

get_gpt_text_format

get_gpt_text_format() -> Any

Get GPT text format.

Purpose

Builds the response-format value accepted by the GPT Chat replacement.

Returns:

Name Type Description
Any Any

GPT response-format configuration.

Source code in app.py
def get_gpt_text_format( ) -> Any:
	"""Get GPT text format.

	Purpose:
		Builds the response-format value accepted by the GPT Chat replacement.

	Returns:
		Any: GPT response-format configuration.
	"""
	selected_format = str( st.session_state.get( 'text_response_format', '', ) or '' ).strip( )

	if not selected_format or selected_format == 'text':
		return None

	if selected_format == 'json_object':
		return { 'type': 'json_object', }

	if selected_format == 'json_schema':
		return { 'type': 'json_schema', 'name': str(
			st.session_state.get( 'text_json_schema_name',
				'response_schema', ) or 'response_schema' ).strip( ),
			'schema': get_text_response_schema( required=True ),
			'strict': bool( st.session_state.get( 'text_json_schema_strict', True, ) ), }

	return selected_format

get_gemini_text_schema

get_gemini_text_schema() -> Optional[Dict[str, Any]]

Get Gemini text schema.

Purpose

Returns a Gemini response schema only when JSON output is selected and schema text has been entered.

Returns:

Type Description
Optional[Dict[str, Any]]

Optional[Dict[str, Any]]: Parsed schema or None.

Source code in app.py
def get_gemini_text_schema( ) -> Optional[ Dict[ str, Any ] ]:
	"""Get Gemini text schema.

	Purpose:
		Returns a Gemini response schema only when JSON output is selected and schema text
		has been entered.

	Returns:
		Optional[Dict[str, Any]]: Parsed schema or None.
	"""
	selected_format = str( st.session_state.get( 'text_response_format', '', ) or '' ).strip( )

	if selected_format != 'application/json':
		return None

	return get_text_response_schema( required=False )

get_grok_text_schema

get_grok_text_schema() -> Any

Get Grok text schema.

Purpose

Returns the required xAI schema only when JSON Schema output is selected.

Returns:

Name Type Description
Any Any

Parsed schema or None.

Source code in app.py
def get_grok_text_schema( ) -> Any:
	"""Get Grok text schema.

	Purpose:
		Returns the required xAI schema only when JSON Schema output is selected.

	Returns:
		Any: Parsed schema or None.
	"""
	selected_format = str( st.session_state.get( 'text_response_format', '', ) or '' ).strip( )

	if selected_format != 'json_schema':
		return None

	return get_text_response_schema( required=True )

validate_text_request

validate_text_request() -> None

Validate text request.

Purpose

Prevents submission when the selected provider operation is missing required provider-specific controls.

Returns:

Name Type Description
None None

This function validates state.

Raises:

Type Description
ValueError

Raised when required request values are missing.

Source code in app.py
def validate_text_request( ) -> None:
	"""Validate text request.

	Purpose:
		Prevents submission when the selected provider operation is missing required
		provider-specific controls.

	Returns:
		None: This function validates state.

	Raises:
		ValueError: Raised when required request values are missing.
	"""
	if not st.session_state.get( 'text_model' ):
		raise ValueError( 'Select a Text model before sending a prompt.' )

	selected_tools = st.session_state.get( 'text_tools', [ ], )

	if provider_name == 'GPT':
		continuation_mode = st.session_state.get( 'text_continuation_mode', 'None', )

		if (continuation_mode == 'Previous Response' and not str(
			st.session_state.get( 'text_previous_response_id', '', ) or '' ).strip( )):
			raise ValueError(
				'Enter a Previous Response ID or select another continuation mode.' )

		if (continuation_mode == 'Conversation' and not str(
			st.session_state.get( 'text_conversation_id', '', ) or '' ).strip( )):
			raise ValueError( 'Enter a Conversation ID or select another continuation mode.' )

		if ('file_search' in selected_tools and not parse_comma_list(
			st.session_state.get( 'text_vector_store_ids', '', ) )):
			raise ValueError(
				'Enter at least one GPT Vector Store ID when File Search is selected.' )

	if provider_name == 'Gemini':
		if ('file_search' in selected_tools and not parse_comma_list(
			st.session_state.get( 'text_vector_store_ids', '', ) )):
			raise ValueError( 'Enter at least one Gemini File Search Store resource name.' )

		if ('url_context' in selected_tools and not parse_semicolon_list(
			st.session_state.get( 'text_urls_input', '', ) )):
			raise ValueError( 'Enter at least one URL when URL Context is selected.' )

	if (
			provider_name == 'Grok' and 'collections_search' in selected_tools and not
	get_selected_grok_collection_ids( )):
		raise ValueError( 'Select or enter at least one xAI Collection.' )

	selected_format = str( st.session_state.get( 'text_response_format', '', ) or '' )

	if (provider_name in [ 'GPT', 'Grok', ] and selected_format == 'json_schema'):
		get_text_response_schema( required=True )

reset_text_model_settings

reset_text_model_settings() -> None

Reset text model settings.

Purpose

Resets Text Mode model and provider-capability selections.

Returns:

Name Type Description
None None

This function updates session state.

Source code in app.py
def reset_text_model_settings( ) -> None:
	"""Reset text model settings.

	Purpose:
		Resets Text Mode model and provider-capability selections.

	Returns:
		None: This function updates session state.
	"""
	st.session_state[ 'text_model' ] = ''
	st.session_state[ 'text_reasoning' ] = ''
	st.session_state[ 'text_safety_profile' ] = ''

reset_text_inference_settings

reset_text_inference_settings() -> None

Reset text inference settings.

Purpose

Resets Text Mode sampling and penalty controls.

Returns:

Name Type Description
None None

This function updates session state.

Source code in app.py
def reset_text_inference_settings( ) -> None:
	"""Reset text inference settings.

	Purpose:
		Resets Text Mode sampling and penalty controls.

	Returns:
		None: This function updates session state.
	"""
	st.session_state[ 'text_temperature' ] = 0.0
	st.session_state[ 'text_top_percent' ] = 0.0
	st.session_state[ 'text_top_k' ] = 0
	st.session_state[ 'text_frequency_penalty' ] = 0.0
	st.session_state[ 'text_presence_penalty' ] = 0.0

reset_text_tool_settings

reset_text_tool_settings() -> None

Reset text tool settings.

Purpose

Resets Text Mode tools, grounding, domains, URLs, and retrieval resources.

Returns:

Name Type Description
None None

This function updates session state.

Source code in app.py
def reset_text_tool_settings( ) -> None:
	"""Reset text tool settings.

	Purpose:
		Resets Text Mode tools, grounding, domains, URLs, and retrieval resources.

	Returns:
		None: This function updates session state.
	"""
	st.session_state[ 'text_tools' ] = [ ]
	st.session_state[ 'text_include' ] = [ ]
	st.session_state[ 'text_tool_choice' ] = ''
	st.session_state[ 'text_max_calls' ] = 0
	st.session_state[ 'text_parallel_tools' ] = False
	st.session_state[ 'text_google_grounding' ] = False
	st.session_state[ 'text_urls_input' ] = ''
	st.session_state[ 'text_max_urls' ] = 0
	st.session_state[ 'text_domains_input' ] = ''
	st.session_state[ 'text_vector_store_ids' ] = ''
	st.session_state[ 'text_grok_collection_labels' ] = [ ]
	st.session_state[ 'text_grok_collection_ids' ] = [ ]
	st.session_state[ 'text_grok_collection_ids_input' ] = ''

reset_text_response_settings

reset_text_response_settings() -> None

Reset text response settings.

Purpose

Resets Text Mode output, structured-response, streaming, storage, and continuation controls.

Returns:

Name Type Description
None None

This function updates session state.

Source code in app.py
def reset_text_response_settings( ) -> None:
	"""Reset text response settings.

	Purpose:
		Resets Text Mode output, structured-response, streaming, storage, and continuation
		controls.

	Returns:
		None: This function updates session state.
	"""
	st.session_state[ 'text_max_tokens' ] = 0
	st.session_state[ 'text_response_format' ] = ''
	st.session_state[ 'text_response_schema' ] = ''
	st.session_state[ 'text_json_schema' ] = ''
	st.session_state[ 'text_json_schema_name' ] = 'response_schema'
	st.session_state[ 'text_json_schema_strict' ] = True
	st.session_state[ 'text_stops_input' ] = ''
	st.session_state[ 'text_store' ] = False
	st.session_state[ 'text_stream' ] = False
	st.session_state[ 'text_background' ] = False
	st.session_state[ 'text_continuation_mode' ] = 'None'
	st.session_state[ 'text_previous_response_id' ] = ''
	st.session_state[ 'text_conversation_id' ] = ''

clear_text_messages

clear_text_messages() -> None

Clear text messages.

Purpose

Clears Text Mode conversation, continuation, answer, and source state.

Returns:

Name Type Description
None None

This function updates session state.

Source code in app.py
def clear_text_messages( ) -> None:
	"""Clear text messages.

	Purpose:
		Clears Text Mode conversation, continuation, answer, and source state.

	Returns:
		None: This function updates session state.
	"""
	st.session_state[ 'text_messages' ] = [ ]
	st.session_state[ 'text_context' ] = [ ]
	st.session_state[ 'text_previous_response_id' ] = ''
	st.session_state[ 'text_conversation_id' ] = ''
	st.session_state[ 'last_answer' ] = ''
	st.session_state[ 'last_sources' ] = [ ]

build_gpt_text_kwargs

build_gpt_text_kwargs(
    prompt: str,
    prior_context: List[Dict[str, str]],
    stream_handler: Any = None,
) -> Dict[str, Any]

Build GPT text arguments.

Purpose

Builds only arguments accepted by the GPT Chat replacement.

Parameters:

Name Type Description Default
prompt str

Current user prompt.

required
prior_context List[Dict[str, str]]

Prior conversation messages.

required
stream_handler Any

Optional streaming callback.

None

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: GPT text-generation arguments.

Source code in app.py
def build_gpt_text_kwargs( prompt: str, prior_context: List[ Dict[ str, str ] ],
	stream_handler: Any = None ) -> Dict[ str, Any ]:
	"""Build GPT text arguments.

	Purpose:
		Builds only arguments accepted by the GPT Chat replacement.

	Args:
		prompt (str): Current user prompt.
		prior_context (List[Dict[str, str]]): Prior conversation messages.
		stream_handler (Any): Optional streaming callback.

	Returns:
		Dict[str, Any]: GPT text-generation arguments.
	"""
	selected_tools = list( st.session_state.get( 'text_tools', [ ], ) )
	continuation_mode = st.session_state.get( 'text_continuation_mode', 'None', )
	previous_id = ''
	conversation_id = ''

	if continuation_mode == 'Previous Response':
		previous_id = str(
			st.session_state.get( 'text_previous_response_id', '', ) or '' ).strip( )
	elif continuation_mode == 'Conversation':
		conversation_id = str(
			st.session_state.get( 'text_conversation_id', '', ) or '' ).strip( )

	return { 'prompt': prompt, 'model': st.session_state.get( 'text_model', '', ),
		'temperature': float( st.session_state.get( 'text_temperature', 0.0, ) ),
		'format': get_gpt_text_format( ),
		'top_p': float( st.session_state.get( 'text_top_percent', 0.0, ) ),
		'frequency': float( st.session_state.get( 'text_frequency_penalty', 0.0, ) ),
		'max_tools': int( st.session_state.get( 'text_max_calls', 0, ) ),
		'presence': float( st.session_state.get( 'text_presence_penalty', 0.0, ) ),
		'max_tokens': int( st.session_state.get( 'text_max_tokens', 0, ) ),
		'store': bool( st.session_state.get( 'text_store', False, ) ),
		'stream': bool( st.session_state.get( 'text_stream', False, ) ),
		'instruct': str( st.session_state.get( 'text_system_instructions', '', ) or '' ),
		'background': bool( st.session_state.get( 'text_background', False, ) ),
		'reasoning': str( st.session_state.get( 'text_reasoning', '', ) or '' ),
		'include': list( st.session_state.get( 'text_include', [ ], ) ),
		'tools': selected_tools, 'allowed_domains': (
			normalize_text_domains( ) if 'web_search' in selected_tools else [ ]),
		'previous_id': previous_id,
		'tool_choice': str( st.session_state.get( 'text_tool_choice', '', ) or '' ),
		'is_parallel': bool( st.session_state.get( 'text_parallel_tools', False, ) ),
		'context': prior_context, 'input_data': None, 'vector_store_ids': (parse_comma_list(
			st.session_state.get( 'text_vector_store_ids',
				'', ) ) if 'file_search' in selected_tools else [ ]),
		'conversation_id': conversation_id, }

build_gemini_text_kwargs

build_gemini_text_kwargs(
    prompt: str,
    prior_context: List[Dict[str, str]],
    stream_handler: Any = None,
) -> Dict[str, Any]

Build Gemini text arguments.

Purpose

Builds only arguments accepted by the Gemini Chat replacement.

Parameters:

Name Type Description Default
prompt str

Current user prompt.

required
prior_context List[Dict[str, str]]

Prior conversation messages.

required
stream_handler Any

Optional streaming callback.

None

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Gemini text-generation arguments.

Source code in app.py
def build_gemini_text_kwargs( prompt: str, prior_context: List[ Dict[ str, str ] ],
	stream_handler: Any = None ) -> Dict[ str, Any ]:
	"""Build Gemini text arguments.

	Purpose:
		Builds only arguments accepted by the Gemini Chat replacement.

	Args:
		prompt (str): Current user prompt.
		prior_context (List[Dict[str, str]]): Prior conversation messages.
		stream_handler (Any): Optional streaming callback.

	Returns:
		Dict[str, Any]: Gemini text-generation arguments.
	"""
	selected_tools = list( st.session_state.get( 'text_tools', [ ], ) )

	if (st.session_state.get( 'text_google_grounding',
		False, ) and 'google_search' not in selected_tools):
		selected_tools.append( 'google_search' )

	return { 'prompt': prompt, 'model': st.session_state.get( 'text_model', '', ), 'number': 1,
		'temperature': float( st.session_state.get( 'text_temperature', 0.0, ) ),
		'top_p': float( st.session_state.get( 'text_top_percent', 0.0, ) ),
		'top_k': int( st.session_state.get( 'text_top_k', 0, ) ),
		'frequency': float( st.session_state.get( 'text_frequency_penalty', 0.0, ) ),
		'presence': float( st.session_state.get( 'text_presence_penalty', 0.0, ) ),
		'max_tokens': int( st.session_state.get( 'text_max_tokens', 0, ) ),
		'stops': parse_comma_list( st.session_state.get( 'text_stops_input', '', ) ),
		'instruct': str( st.session_state.get( 'text_system_instructions', '', ) or '' ),
		'response_format': str( st.session_state.get( 'text_response_format', '', ) or '' ),
		'tools': selected_tools, 'tool_choice': '',
		'reasoning': str( st.session_state.get( 'text_reasoning', '', ) or '' ),
		'modalities': [ ], 'media_resolution': '', 'context': prior_context, 'content': '',
		'urls': (parse_semicolon_list( st.session_state.get( 'text_urls_input',
			'', ) ) if 'url_context' in selected_tools else [ ]),
		'max_urls': int( st.session_state.get( 'text_max_urls', 0, ) ),
		'response_schema': get_gemini_text_schema( ),
		'safety_profile': str( st.session_state.get( 'text_safety_profile', '', ) or '' ),
		'file_search_store_names': (parse_comma_list(
			st.session_state.get( 'text_vector_store_ids',
				'', ) ) if 'file_search' in selected_tools else [ ]),
		'stream': bool( st.session_state.get( 'text_stream', False, ) ),
		'stream_handler': stream_handler, }

build_grok_text_kwargs

build_grok_text_kwargs(
    prompt: str,
    prior_context: List[Dict[str, str]],
    stream_handler: Any = None,
) -> Dict[str, Any]

Build Grok text arguments.

Purpose

Builds only arguments accepted by the Grok Chat replacement.

Parameters:

Name Type Description Default
prompt str

Current user prompt.

required
prior_context List[Dict[str, str]]

Prior conversation messages.

required
stream_handler Any

Optional streaming callback.

None

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Grok text-generation arguments.

Source code in app.py
def build_grok_text_kwargs( prompt: str, prior_context: List[ Dict[ str, str ] ],
	stream_handler: Any = None ) -> Dict[ str, Any ]:
	"""Build Grok text arguments.

	Purpose:
		Builds only arguments accepted by the Grok Chat replacement.

	Args:
		prompt (str): Current user prompt.
		prior_context (List[Dict[str, str]]): Prior conversation messages.
		stream_handler (Any): Optional streaming callback.

	Returns:
		Dict[str, Any]: Grok text-generation arguments.
	"""
	selected_tools = list( st.session_state.get( 'text_tools', [ ], ) )

	return { 'prompt': prompt, 'model': st.session_state.get( 'text_model', '', ),
		'temperature': float( st.session_state.get( 'text_temperature', 0.0, ) ),
		'format': str( st.session_state.get( 'text_response_format', '', ) or '' ),
		'top_p': float( st.session_state.get( 'text_top_percent', 0.0, ) ),
		'frequency': float( st.session_state.get( 'text_frequency_penalty', 0.0, ) ),
		'presence': float( st.session_state.get( 'text_presence_penalty', 0.0, ) ),
		'max_tokens': int( st.session_state.get( 'text_max_tokens', 0, ) ),
		'stops': parse_comma_list( st.session_state.get( 'text_stops_input', '', ) ),
		'store': bool( st.session_state.get( 'text_store', False, ) ),
		'stream': bool( st.session_state.get( 'text_stream', False, ) ),
		'instruct': str( st.session_state.get( 'text_system_instructions', '', ) or '' ),
		'reasoning': str( st.session_state.get( 'text_reasoning', '', ) or '' ),
		'include': list( st.session_state.get( 'text_include', [ ], ) ),
		'tools': selected_tools, 'allowed_domains': (
			normalize_text_domains( ) if 'web_search' in selected_tools else [ ]),
		'previous_id': str(
			st.session_state.get( 'text_previous_response_id', '', ) or '' ).strip( ),
		'tool_choice': str( st.session_state.get( 'text_tool_choice', '', ) or '' ),
		'is_parallel': bool( st.session_state.get( 'text_parallel_tools', False, ) ),
		'context': prior_context, 'vector_store_ids': (
			get_selected_grok_collection_ids( ) if 'collections_search' in selected_tools else
			[ ]),
		'max_tools': int( st.session_state.get( 'text_max_calls', 0, ) ),
		'response_schema': get_grok_text_schema( ), 'stream_handler': stream_handler, }

call_generate_text

call_generate_text(
    prompt: str,
    prior_context: List[Dict[str, str]],
    stream_handler: Any = None,
) -> Any

Call generate text.

Purpose

Dispatches Text Mode through the exact replacement interface for the selected provider.

Parameters:

Name Type Description Default
prompt str

Current user prompt.

required
prior_context List[Dict[str, str]]

Prior conversation messages.

required
stream_handler Any

Optional streaming callback.

None

Returns:

Name Type Description
Any Any

Provider-generated text.

Source code in app.py
def call_generate_text( prompt: str, prior_context: List[ Dict[ str, str ] ],
	stream_handler: Any = None ) -> Any:
	"""Call generate text.

	Purpose:
		Dispatches Text Mode through the exact replacement interface for the selected
		provider.

	Args:
		prompt (str): Current user prompt.
		prior_context (List[Dict[str, str]]): Prior conversation messages.
		stream_handler (Any): Optional streaming callback.

	Returns:
		Any: Provider-generated text.
	"""
	if provider_name == 'GPT':
		return text.generate_text(
			**build_gpt_text_kwargs( prompt, prior_context, stream_handler, ) )

	if provider_name == 'Gemini':
		return text.generate_text(
			**build_gemini_text_kwargs( prompt, prior_context, stream_handler, ) )

	if provider_name == 'Grok':
		return text.generate_text(
			**build_grok_text_kwargs( prompt, prior_context, stream_handler, ) )

	raise ValueError( f'Unsupported Text provider: {provider_name}' )

get_text_avatar

get_text_avatar(role: str) -> str

Get text avatar.

Purpose

Returns the configured assistant avatar for the selected provider.

Parameters:

Name Type Description Default
role str

Message role.

required

Returns:

Name Type Description
str str

Avatar value.

Source code in app.py
def get_text_avatar( role: str ) -> str:
	"""Get text avatar.

	Purpose:
		Returns the configured assistant avatar for the selected provider.

	Args:
		role (str): Message role.

	Returns:
		str: Avatar value.
	"""
	if role != 'assistant':
		return ''

	if provider_name == 'GPT':
		return getattr( cfg, 'GPT', getattr( cfg, 'BOO', '🧠' ), )

	if provider_name == 'Gemini':
		return getattr( cfg, 'JENI', getattr( cfg, 'BOO', '🧠' ), )

	if provider_name == 'Grok':
		return getattr( cfg, 'GROK', getattr( cfg, 'BOO', '🧠' ), )

	return getattr( cfg, 'BOO', '🧠', )

extract_text_sources

extract_text_sources(
    instance: Any, response: Any
) -> List[Dict[str, Any]]

Extract text sources.

Purpose

Extracts provider-specific grounding and search sources from the latest response.

Parameters:

Name Type Description Default
instance Any

Selected provider wrapper.

required
response Any

Provider response.

required

Returns:

Type Description
List[Dict[str, Any]]

List[Dict[str, Any]]: Normalized source records.

Source code in app.py
def extract_text_sources( instance: Any, response: Any ) -> List[ Dict[ str, Any ] ]:
	"""Extract text sources.

	Purpose:
		Extracts provider-specific grounding and search sources from the latest response.

	Args:
		instance (Any): Selected provider wrapper.
		response (Any): Provider response.

	Returns:
		List[Dict[str, Any]]: Normalized source records.
	"""
	sources: List[ Dict[ str, Any ] ] = [ ]

	if (provider_name == 'Gemini' and hasattr( instance, 'get_grounding_sources', )):
		result = instance.get_grounding_sources( )

		if isinstance( result, list ):
			sources = result

	elif (provider_name in [ 'GPT', 'Grok', ] and hasattr( instance, 'get_sources', )):
		result = instance.get_sources( )

		if isinstance( result, list ):
			sources = result

	elif 'extract_sources' in globals( ):
		result = extract_sources( response )

		if isinstance( result, list ):
			sources = result

	return sources

update_text_usage

update_text_usage(response: Any) -> None

Update text usage.

Purpose

Updates application token counters from the latest provider response when the application usage helper is available.

Parameters:

Name Type Description Default
response Any

Provider response.

required

Returns:

Name Type Description
None None

This function updates application state.

Source code in app.py
def update_text_usage( response: Any ) -> None:
	"""Update text usage.

	Purpose:
		Updates application token counters from the latest provider response when the
		application usage helper is available.

	Args:
		response (Any): Provider response.

	Returns:
		None: This function updates application state.
	"""
	if 'update_token_counters' in globals( ):
		update_token_counters( response )

load_text_instruction_template

load_text_instruction_template() -> None

Load Text instruction template.

Purpose

Loads the selected prompt template into the Text Mode system-instruction field.

Returns:

Name Type Description
None None

This function updates Text Mode session state.

Source code in app.py
def load_text_instruction_template( ) -> None:
	"""Load Text instruction template.

	Purpose:
	    Loads the selected prompt template into the Text Mode system-instruction field.

	Returns:
	    None: This function updates Text Mode session state.
	"""
	load_prompt_template( prompt_id_key='text_prompt_id',
		instructions_key='text_system_instructions', )

clear_text_instructions

clear_text_instructions() -> None

Clear Text instructions.

Purpose

Clears the Text Mode system instructions and its selected prompt template.

Returns:

Name Type Description
None None

This function updates Text Mode session state.

Source code in app.py
def clear_text_instructions( ) -> None:
	"""Clear Text instructions.

	Purpose:
	    Clears the Text Mode system instructions and its selected prompt template.

	Returns:
	    None: This function updates Text Mode session state.
	"""
	st.session_state[ 'text_system_instructions' ] = ''
	st.session_state[ 'text_prompt_id' ] = None

convert_text_system_instructions

convert_text_system_instructions() -> None

Convert Text system instructions.

Purpose

Converts the Text Mode system instructions between Markdown headings and XML-style heading elements.

Returns:

Name Type Description
None None

This function updates Text Mode session state.

Source code in app.py
def convert_text_system_instructions( ) -> None:
	"""Convert Text system instructions.

	Purpose:
	    Converts the Text Mode system instructions between Markdown headings and XML-style
	    heading elements.

	Returns:
	    None: This function updates Text Mode session state.
	"""
	instructions = str( st.session_state.get( 'text_system_instructions', '' ) or '' )

	if not instructions.strip( ):
		return

	st.session_state[ 'text_system_instructions' ] = convert_markdown( instructions )

on_stream_chunk

on_stream_chunk(chunk: str) -> None

On stream chunk.

Purpose

Renders the accumulated provider streaming response.

Parameters:

Name Type Description Default
chunk str

Provider text delta.

required

Returns:

Name Type Description
None None

This function updates the streaming placeholder.

Source code in app.py
def on_stream_chunk( chunk: str ) -> None:
	"""On stream chunk.

	Purpose:
		Renders the accumulated provider streaming response.

	Args:
		chunk (str): Provider text delta.

	Returns:
		None: This function updates the streaming placeholder.
	"""
	if chunk is None:
		return

	chunk_text = str( chunk )

	if not chunk_text:
		return

	stream_buffer.append( chunk_text )
	stream_placeholder.markdown( ''.join( stream_buffer ) + '▌' )

get_image_options

get_image_options(
    instance: Any,
    attr_name: str,
    fallback: Optional[List[str]] = None,
) -> List[str]

Get image options.

Purpose

Returns normalized image options exposed by the selected provider wrapper.

Parameters:

Name Type Description Default
instance Any

Provider image-wrapper instance.

required
attr_name str

Wrapper option-property name.

required
fallback Optional[List[str]]

Values used when the property is unavailable.

None

Returns:

Type Description
List[str]

List[str]: Normalized provider option values.

Source code in app.py
def get_image_options( instance: Any, attr_name: str,
	fallback: Optional[ List[ str ] ] = None ) -> List[ str ]:
	"""Get image options.

	Purpose:
		Returns normalized image options exposed by the selected provider wrapper.

	Args:
		instance (Any): Provider image-wrapper instance.
		attr_name (str): Wrapper option-property name.
		fallback (Optional[List[str]]): Values used when the property is unavailable.

	Returns:
		List[str]: Normalized provider option values.
	"""
	values = getattr( instance, attr_name, None, )

	if callable( values ):
		values = values( )

	if values is None:
		values = fallback or [ ]

	if isinstance( values, tuple ):
		values = list( values )

	if not isinstance( values, list ):
		return fallback or [ ]

	return [ str( value ) for value in values if str( value ).strip( ) ]

sanitize_image_selection

sanitize_image_selection(
    key: str, valid_options: List[str], default: Any = ""
) -> None

Sanitize image selection.

Purpose

Removes stale single-select values that are unsupported by the selected provider and image operation.

Parameters:

Name Type Description Default
key str

Session-state key.

required
valid_options List[str]

Supported option values.

required
default Any

Replacement value.

''

Returns:

Name Type Description
None None

This function updates session state.

Source code in app.py
def sanitize_image_selection( key: str, valid_options: List[ str ], default: Any = '' ) -> \
		None:
	"""Sanitize image selection.

	Purpose:
		Removes stale single-select values that are unsupported by the selected provider
		and image operation.

	Args:
		key (str): Session-state key.
		valid_options (List[str]): Supported option values.
		default (Any): Replacement value.

	Returns:
		None: This function updates session state.
	"""
	current_value = st.session_state.get( key, default, )

	if current_value in [ None, '', ]:
		return

	if valid_options and current_value not in valid_options:
		st.session_state[ key ] = default

sanitize_image_multiselect

sanitize_image_multiselect(
    key: str, valid_options: List[str]
) -> None

Sanitize image multiselect.

Purpose

Removes stale multi-select values that are unsupported by the selected provider.

Parameters:

Name Type Description Default
key str

Session-state key.

required
valid_options List[str]

Supported option values.

required

Returns:

Name Type Description
None None

This function updates session state.

Source code in app.py
def sanitize_image_multiselect( key: str, valid_options: List[ str ] ) -> None:
	"""Sanitize image multiselect.

	Purpose:
		Removes stale multi-select values that are unsupported by the selected provider.

	Args:
		key (str): Session-state key.
		valid_options (List[str]): Supported option values.

	Returns:
		None: This function updates session state.
	"""
	current_values = st.session_state.get( key, [ ], )

	if not isinstance( current_values, list ):
		st.session_state[ key ] = [ ]
		return

	st.session_state[ key ] = [ value for value in current_values if value in valid_options ]

get_provider_image_models

get_provider_image_models(
    selected_mode: Optional[str],
) -> List[str]

Get provider image models.

Purpose

Returns models configured for the selected provider and image operation.

Parameters:

Name Type Description Default
selected_mode Optional[str]

Generation, Analysis, or Editing.

required

Returns:

Type Description
List[str]

List[str]: Available model identifiers.

Source code in app.py
def get_provider_image_models( selected_mode: Optional[ str ] ) -> List[ str ]:
	"""Get provider image models.

	Purpose:
		Returns models configured for the selected provider and image operation.

	Args:
		selected_mode (Optional[str]): Generation, Analysis, or Editing.

	Returns:
		List[str]: Available model identifiers.
	"""
	mode_name = selected_mode or ''

	if provider_name == 'GPT':
		if mode_name == 'Generation':
			models = list( getattr( cfg, 'GPT_GENERATION', [ ], ) )

			if models:
				return models

		if mode_name == 'Analysis':
			models = list( getattr( cfg, 'GPT_ANALYSIS', [ ], ) )

			if models:
				return models

		if mode_name == 'Editing':
			models = list( getattr( cfg, 'GPT_EDITING', [ ], ) )

			if models:
				return models

	if provider_name == 'Gemini':
		if mode_name == 'Generation':
			models = list( getattr( cfg, 'GEMINI_GENERATION', [ ], ) )

			if models:
				return models

		if mode_name == 'Analysis':
			models = list( getattr( cfg, 'GEMINI_ANALYSIS', [ ], ) )

			if models:
				return models

		if mode_name == 'Editing':
			models = list( getattr( cfg, 'GEMINI_EDITING', [ ], ) )

			if models:
				return models

	if provider_name == 'Grok':
		if mode_name == 'Analysis':
			models = get_image_options( image, 'analysis_model_options', )

			if models:
				return models

			models = list( getattr( cfg, 'GROK_ANALYSIS', [ ], ) )

			if models:
				return models

		if mode_name == 'Generation':
			models = list( getattr( cfg, 'GROK_GENERATION', [ ], ) )

			if models:
				return models

		if mode_name == 'Editing':
			models = list( getattr( cfg, 'GROK_EDITING', [ ], ) )

			if models:
				return models

	models = get_image_options( image, 'model_options', )

	if not models:
		model_value = str( getattr( image, 'model', '', ) or '' )

		if model_value:
			models = [ model_value, ]

	return models

get_selected_image_model

get_selected_image_model(operation: str) -> str

Get selected image model.

Purpose

Returns the model selected for the requested image operation.

Parameters:

Name Type Description Default
operation str

Generation, Analysis, or Editing.

required

Returns:

Name Type Description
str str

Selected model identifier.

Source code in app.py
def get_selected_image_model( operation: str ) -> str:
	"""Get selected image model.

	Purpose:
		Returns the model selected for the requested image operation.

	Args:
		operation (str): Generation, Analysis, or Editing.

	Returns:
		str: Selected model identifier.
	"""
	if operation == 'Generation':
		return str(
			st.session_state.get( 'image_generation_model', '', ) or st.session_state.get(
				'image_model', '', ) or '' )

	if operation == 'Analysis':
		return str( st.session_state.get( 'image_analysis_model', '',
		) or st.session_state.get(
			'image_model', '', ) or '' )

	if operation == 'Editing':
		return str( st.session_state.get( 'image_editing_model', '', ) or st.session_state.get(
			'image_model', '', ) or '' )

	return ''

save_uploaded_image

save_uploaded_image(uploaded_file: Any) -> Optional[str]

Save uploaded image.

Purpose

Persists an uploaded image to a temporary local file for provider requests.

Parameters:

Name Type Description Default
uploaded_file Any

Streamlit uploaded-file object.

required

Returns:

Type Description
Optional[str]

Optional[str]: Temporary local path or None.

Source code in app.py
def save_uploaded_image( uploaded_file: Any ) -> Optional[ str ]:
	"""Save uploaded image.

	Purpose:
		Persists an uploaded image to a temporary local file for provider requests.

	Args:
		uploaded_file (Any): Streamlit uploaded-file object.

	Returns:
		Optional[str]: Temporary local path or None.
	"""
	if uploaded_file is None:
		return None

	if 'save_temp' in globals( ):
		return save_temp( uploaded_file )

	import tempfile
	from pathlib import Path

	suffix = Path( uploaded_file.name ).suffix or '.png'

	with tempfile.NamedTemporaryFile( delete=False, suffix=suffix, ) as temporary_file:
		temporary_file.write( uploaded_file.getvalue( ) )
		return temporary_file.name

append_image_message

append_image_message(role: str, content: str) -> None

Append image message.

Purpose

Appends an Images Mode conversation message.

Parameters:

Name Type Description Default
role str

Message role.

required
content str

Message content.

required

Returns:

Name Type Description
None None

This function updates session state.

Source code in app.py
def append_image_message( role: str, content: str ) -> None:
	"""Append image message.

	Purpose:
		Appends an Images Mode conversation message.

	Args:
		role (str): Message role.
		content (str): Message content.

	Returns:
		None: This function updates session state.
	"""
	if not isinstance( st.session_state.get( 'image_input' ), list, ):
		st.session_state[ 'image_input' ] = [ ]

	st.session_state[ 'image_input' ].append( { 'role': role, 'content': content, } )

render_image_messages

render_image_messages() -> None

Render image messages.

Purpose

Renders Images Mode conversation messages.

Returns:

Name Type Description
None None

This function renders Streamlit content.

Source code in app.py
def render_image_messages( ) -> None:
	"""Render image messages.

	Purpose:
		Renders Images Mode conversation messages.

	Returns:
		None: This function renders Streamlit content.
	"""
	if not isinstance( st.session_state.get( 'image_input' ), list, ):
		st.session_state[ 'image_input' ] = [ ]

	for message in st.session_state.get( 'image_input', [ ], ):
		if not isinstance( message, dict, ):
			continue

		with st.chat_message( message.get( 'role', 'assistant', ), avatar='', ):
			st.markdown( message.get( 'content', '', ) )

clear_image_messages

clear_image_messages() -> None

Clear image messages.

Purpose

Clears Images Mode message and result collections.

Returns:

Name Type Description
None None

This function updates session state.

Source code in app.py
def clear_image_messages( ) -> None:
	"""Clear image messages.

	Purpose:
		Clears Images Mode message and result collections.

	Returns:
		None: This function updates session state.
	"""
	st.session_state[ 'image_input' ] = [ ]
	st.session_state[ 'generated_images' ] = [ ]
	st.session_state[ 'analyzed_images' ] = [ ]
	st.session_state[ 'edited_images' ] = [ ]

clear_image_instructions

clear_image_instructions() -> None

Clear image instructions.

Purpose

Clears Images Mode system instructions.

Returns:

Name Type Description
None None

This function updates session state.

Source code in app.py
def clear_image_instructions( ) -> None:
	"""Clear image instructions.

	Purpose:
		Clears Images Mode system instructions.

	Returns:
		None: This function updates session state.
	"""
	st.session_state[ 'image_system_instructions' ] = ''

convert_image_system_instructions

convert_image_system_instructions() -> None

Convert image system instructions.

Purpose

Converts Images Mode instructions between XML and Markdown.

Returns:

Name Type Description
None None

This function updates session state.

Source code in app.py
def convert_image_system_instructions( ) -> None:
	"""Convert image system instructions.

	Purpose:
		Converts Images Mode instructions between XML and Markdown.

	Returns:
		None: This function updates session state.
	"""
	text_value = str( st.session_state.get( 'image_system_instructions', '', ) or '' ).strip( )

	if not text_value:
		return

	if cfg.XML_BLOCK_PATTERN.search( text_value ):
		converted = convert_xml( text_value )
	else:
		converted = convert_markdown( text_value )

	st.session_state[ 'image_system_instructions' ] = converted

load_image_instruction_template

load_image_instruction_template() -> None

Load image instruction template.

Purpose

Loads the selected Images Mode prompt template into system instructions.

Returns:

Name Type Description
None None

This function updates session state.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in app.py
def load_image_instruction_template( ) -> None:
	"""Load image instruction template.

	Purpose:
		Loads the selected Images Mode prompt template into system instructions.

	Returns:
		None: This function updates session state.

	Raises:
		Error: Re-raised after the exception is logged.
	"""
	try:
		load_prompt_template( prompt_id_key='image_prompt_id',
			instructions_key='image_system_instructions', )
	except Exception as e:
		ex = Error( e )
		ex.module = 'app'
		ex.cause = 'Images Mode'
		ex.method = ('load_image_instruction_template( ) -> None')
		Logger( ).write( ex )
		raise ex

reset_image_model_settings

reset_image_model_settings() -> None

Reset image model settings.

Purpose

Resets Images Mode operation and model selections.

Returns:

Name Type Description
None None

This function updates session state.

Source code in app.py
def reset_image_model_settings( ) -> None:
	"""Reset image model settings.

	Purpose:
		Resets Images Mode operation and model selections.

	Returns:
		None: This function updates session state.
	"""
	st.session_state[ 'image_mode' ] = 'Generation'
	st.session_state[ 'image_model' ] = ''
	st.session_state[ 'image_generation_model' ] = ''
	st.session_state[ 'image_analysis_model' ] = ''
	st.session_state[ 'image_editing_model' ] = ''
	st.session_state[ 'image_number' ] = 1

reset_image_inference_settings

reset_image_inference_settings() -> None

Reset image inference settings.

Purpose

Resets provider-supported image inference controls.

Returns:

Name Type Description
None None

This function updates session state.

Source code in app.py
def reset_image_inference_settings( ) -> None:
	"""Reset image inference settings.

	Purpose:
		Resets provider-supported image inference controls.

	Returns:
		None: This function updates session state.
	"""
	st.session_state[ 'image_temperature' ] = 0.0
	st.session_state[ 'image_top_percent' ] = 0.0
	st.session_state[ 'image_top_k' ] = 0
	st.session_state[ 'image_frequency_penalty' ] = 0.0
	st.session_state[ 'image_presence_penalty' ] = 0.0
	st.session_state[ 'image_max_tokens' ] = 0

reset_image_response_settings

reset_image_response_settings() -> None

Reset image response settings.

Purpose

Resets provider-supported image analysis response controls.

Returns:

Name Type Description
None None

This function updates session state.

Source code in app.py
def reset_image_response_settings( ) -> None:
	"""Reset image response settings.

	Purpose:
		Resets provider-supported image analysis response controls.

	Returns:
		None: This function updates session state.
	"""
	st.session_state[ 'image_include' ] = [ ]
	st.session_state[ 'image_store' ] = False
	st.session_state[ 'image_stream' ] = False
	st.session_state[ 'image_analysis_detail' ] = 'auto'
	st.session_state[ 'image_media_resolution' ] = ''

reset_image_visual_settings

reset_image_visual_settings() -> None

Reset image visual settings.

Purpose

Resets provider-supported generation and editing output controls.

Returns:

Name Type Description
None None

This function updates session state.

Source code in app.py
def reset_image_visual_settings( ) -> None:
	"""Reset image visual settings.

	Purpose:
		Resets provider-supported generation and editing output controls.

	Returns:
		None: This function updates session state.
	"""
	st.session_state[ 'image_size' ] = ''
	st.session_state[ 'image_quality' ] = ''
	st.session_state[ 'image_style' ] = ''
	st.session_state[ 'image_mime_type' ] = ''
	st.session_state[ 'image_compression' ] = 0.0
	st.session_state[ 'image_backcolor' ] = ''
	st.session_state[ 'image_aspect_ratio' ] = ''
	st.session_state[ 'image_modality' ] = ''
	st.session_state[ 'image_grounded' ] = False
	st.session_state[ 'image_image_search' ] = False

render_image_output

render_image_output(result: Any, caption: str) -> bool

Render image output.

Purpose

Renders provider image URLs, byte content, lists, or compatible image objects.

Parameters:

Name Type Description Default
result Any

Provider image output.

required
caption str

Image caption.

required

Returns:

Name Type Description
bool bool

True when at least one image is rendered.

Source code in app.py
def render_image_output( result: Any, caption: str ) -> bool:
	"""Render image output.

	Purpose:
		Renders provider image URLs, byte content, lists, or compatible image objects.

	Args:
		result (Any): Provider image output.
		caption (str): Image caption.

	Returns:
		bool: True when at least one image is rendered.
	"""
	if result is None:
		return False

	if isinstance( result, list ):
		rendered = False

		for index, item in enumerate( result, start=1, ):
			if render_image_output( item, f'{caption} {index}', ):
				rendered = True

		return rendered

	if isinstance( result, (str, bytes, bytearray,), ):
		st.image( result, caption=caption, use_container_width=True, )
		return True

	result_url = getattr( result, 'url', '', )

	if result_url:
		st.image( result_url, caption=caption, use_container_width=True, )
		return True

	result_bytes = getattr( result, 'image_bytes', None, )

	if result_bytes:
		st.image( result_bytes, caption=caption, use_container_width=True, )
		return True

	try:
		st.image( result, caption=caption, use_container_width=True, )
		return True
	except Exception:
		return False

update_image_usage

update_image_usage(response: Any) -> None

Update image usage.

Purpose

Updates application usage counters when a compatible usage helper is available.

Parameters:

Name Type Description Default
response Any

Provider response.

required

Returns:

Name Type Description
None None

This function updates application state.

Source code in app.py
def update_image_usage( response: Any ) -> None:
	"""Update image usage.

	Purpose:
		Updates application usage counters when a compatible usage helper is available.

	Args:
		response (Any): Provider response.

	Returns:
		None: This function updates application state.
	"""
	if 'update_token_counters' in globals( ):
		update_token_counters( response )

validate_image_request

validate_image_request(
    operation: str, prompt: str, path: str = ""
) -> str

Validate image request.

Purpose

Validates required Images Mode controls for the selected provider operation.

Parameters:

Name Type Description Default
operation str

Generation, Analysis, or Editing.

required
prompt str

Operation prompt.

required
path str

Optional required local image path.

''

Returns:

Name Type Description
str str

Selected provider model.

Raises:

Type Description
ValueError

Raised when a required input is missing.

Source code in app.py
def validate_image_request( operation: str, prompt: str, path: str = '' ) -> str:
	"""Validate image request.

	Purpose:
		Validates required Images Mode controls for the selected provider operation.

	Args:
		operation (str): Generation, Analysis, or Editing.
		prompt (str): Operation prompt.
		path (str): Optional required local image path.

	Returns:
		str: Selected provider model.

	Raises:
		ValueError: Raised when a required input is missing.
	"""
	if not isinstance( prompt, str, ) or not prompt.strip( ):
		raise ValueError( f'Enter an {operation.lower( )} prompt.' )

	model = get_selected_image_model( operation )

	if not model:
		raise ValueError( f'Select a model for Image {operation}.' )

	if operation in [ 'Analysis', 'Editing', ] and not path:
		raise ValueError( f'Upload an image before {operation.lower( )}.' )

	if (provider_name == 'Gemini' and operation in [ 'Generation',
		'Editing', ] and st.session_state.get( 'image_image_search', False, ) and hasattr(
		image, 'supports_image_search', ) and not image.supports_image_search( model )):
		raise ValueError( 'The selected Gemini model does not support Image Search.' )

	if (provider_name == 'Gemini' and operation in [ 'Generation',
		'Editing', ] and st.session_state.get( 'image_grounded', False, ) and hasattr( image,
		'supports_grounding', ) and not image.supports_grounding( model )):
		raise ValueError( 'The selected Gemini model does not support Google grounding.' )

	return model

run_image_generation

run_image_generation(prompt: str) -> Any

Run image generation.

Purpose

Calls the exact generation interface implemented by the selected provider wrapper.

Parameters:

Name Type Description Default
prompt str

Image-generation prompt.

required

Returns:

Name Type Description
Any Any

Provider image output.

Source code in app.py
def run_image_generation( prompt: str ) -> Any:
	"""Run image generation.

	Purpose:
		Calls the exact generation interface implemented by the selected provider wrapper.

	Args:
		prompt (str): Image-generation prompt.

	Returns:
		Any: Provider image output.
	"""
	model = validate_image_request( 'Generation', prompt, )

	if provider_name == 'GPT':
		return image.generate( prompt=prompt,
			number=int( st.session_state.get( 'image_number', 1, ) ), model=model,
			size=str( st.session_state.get( 'image_size', '', ) or '1024x1024' ),
			quality=str( st.session_state.get( 'image_quality', '', ) or 'auto' ),
			fmt=str( st.session_state.get( 'image_mime_type', '', ) or 'png' ).replace(
				'image/', '', ),
			compression=float( st.session_state.get( 'image_compression', 0.0, ) ),
			background=str( st.session_state.get( 'image_backcolor', '', ) or '' ), )

	if provider_name == 'Gemini':
		return image.generate( prompt=prompt, model=model,
			number=int( st.session_state.get( 'image_number', 1, ) ),
			aspect_ratio=str( st.session_state.get( 'image_aspect_ratio', '', ) or '' ),
			image_size=str( st.session_state.get( 'image_size', '', ) or '' ),
			output_mime_type=str( st.session_state.get( 'image_mime_type', '', ) or '' ),
			response_modalities=str( st.session_state.get( 'image_modality', '', ) or '' ),
			temperature=float( st.session_state.get( 'image_temperature', 0.0, ) ),
			top_p=float( st.session_state.get( 'image_top_percent', 0.0, ) ),
			frequency=float( st.session_state.get( 'image_frequency_penalty', 0.0, ) ),
			presence=float( st.session_state.get( 'image_presence_penalty', 0.0, ) ),
			max_tokens=int( st.session_state.get( 'image_max_tokens', 0, ) ),
			media_resolution=str( st.session_state.get( 'image_media_resolution', '', ) or '' ),
			instruct=str( st.session_state.get( 'image_system_instructions', '', ) or '' ),
			grounded=bool( st.session_state.get( 'image_grounded', False, ) ),
			image_search=bool( st.session_state.get( 'image_image_search', False, ) ), )

	if provider_name == 'Grok':
		return image.generate( prompt=prompt, model=model,
			number=int( st.session_state.get( 'image_number', 1, ) ), aspect_ratio=str(
				st.session_state.get( 'image_aspect_ratio', 'auto', ) or 'auto' ), )

	raise ValueError( f'Unsupported Images provider: {provider_name}' )

run_image_analysis

run_image_analysis(prompt: str, path: str) -> Any

Run image analysis.

Purpose

Calls the exact image-analysis interface implemented by the selected provider wrapper.

Parameters:

Name Type Description Default
prompt str

Image-analysis prompt.

required
path str

Local image path.

required

Returns:

Name Type Description
Any Any

Provider analysis text.

Source code in app.py
def run_image_analysis( prompt: str, path: str ) -> Any:
	"""Run image analysis.

	Purpose:
		Calls the exact image-analysis interface implemented by the selected provider
		wrapper.

	Args:
		prompt (str): Image-analysis prompt.
		path (str): Local image path.

	Returns:
		Any: Provider analysis text.
	"""
	model = validate_image_request( 'Analysis', prompt, path, )

	if provider_name == 'GPT':
		return image.analyze( text=prompt, path=path,
			instruct=str( st.session_state.get( 'image_system_instructions', '', ) or '' ),
			model=model, max_tokens=int( st.session_state.get( 'image_max_tokens', 0, ) ),
			temperature=float( st.session_state.get( 'image_temperature', 0.0, ) ),
			include=list( st.session_state.get( 'image_include', [ ], ) ),
			store=bool( st.session_state.get( 'image_store', False, ) ),
			stream=bool( st.session_state.get( 'image_stream', False, ) ),
			detail=str( st.session_state.get( 'image_analysis_detail', 'auto', ) or 'auto' ), )

	if provider_name == 'Gemini':
		return image.analyze( prompt=prompt, path=path, model=model,
			temperature=float( st.session_state.get( 'image_temperature', 0.0, ) ),
			top_p=float( st.session_state.get( 'image_top_percent', 0.0, ) ),
			frequency=float( st.session_state.get( 'image_frequency_penalty', 0.0, ) ),
			presence=float( st.session_state.get( 'image_presence_penalty', 0.0, ) ),
			max_tokens=int( st.session_state.get( 'image_max_tokens', 0, ) ),
			media_resolution=str( st.session_state.get( 'image_media_resolution', '',
			) or '' ),
			instruct=str( st.session_state.get( 'image_system_instructions', '', ) or '' ), )

	if provider_name == 'Grok':
		return image.analyze( prompt=prompt, path=path, model=model,
			detail=str( st.session_state.get( 'image_analysis_detail', 'auto', ) or 'auto' ), )

	raise ValueError( f'Unsupported Images provider: {provider_name}' )

run_image_editing

run_image_editing(
    prompt: str, path: str, mask_path: str = ""
) -> Any

Run image editing.

Purpose

Calls the exact image-editing interface implemented by the selected provider wrapper.

Parameters:

Name Type Description Default
prompt str

Image-editing prompt.

required
path str

Local source-image path.

required
mask_path str

Optional GPT mask path.

''

Returns:

Name Type Description
Any Any

Provider edited-image output.

Source code in app.py
def run_image_editing( prompt: str, path: str, mask_path: str = '' ) -> Any:
	"""Run image editing.

	Purpose:
		Calls the exact image-editing interface implemented by the selected provider
		wrapper.

	Args:
		prompt (str): Image-editing prompt.
		path (str): Local source-image path.
		mask_path (str): Optional GPT mask path.

	Returns:
		Any: Provider edited-image output.
	"""
	model = validate_image_request( 'Editing', prompt, path, )

	if provider_name == 'GPT':
		edit_method = getattr( image, 'edit', None, )

		if not callable( edit_method ):
			raise AttributeError( 'GPT Images does not expose edit().' )

		edit_parameters = inspect.signature( edit_method ).parameters
		edit_kwargs: Dict[ str, Any ] = { 'prompt': prompt, 'path': path, 'model': model,
			'size': str( st.session_state.get( 'image_size', '', ) or '1024x1024' ),
			'quality': str( st.session_state.get( 'image_quality', '', ) or 'auto' ),
			'fmt': str( st.session_state.get( 'image_mime_type', '', ) or 'png' ).replace(
				'image/', '', ),
			'compression': float( st.session_state.get( 'image_compression', 0.0, ) ),
			'background': str( st.session_state.get( 'image_backcolor', '', ) or '' ),
			'number': int( st.session_state.get( 'image_number', 1, ) ), }

		if mask_path:
			if 'mask_path' in edit_parameters:
				edit_kwargs[ 'mask_path' ] = mask_path
			elif 'mask' in edit_parameters:
				edit_kwargs[ 'mask' ] = mask_path

		return edit_method( **edit_kwargs )

	if provider_name == 'Gemini':
		return image.edit( prompt=prompt, path=path, model=model,
			number=int( st.session_state.get( 'image_number', 1, ) ),
			aspect_ratio=str( st.session_state.get( 'image_aspect_ratio', '', ) or '' ),
			image_size=str( st.session_state.get( 'image_size', '', ) or '' ),
			output_mime_type=str( st.session_state.get( 'image_mime_type', '', ) or '' ),
			response_modalities=str( st.session_state.get( 'image_modality', '', ) or '' ),
			temperature=float( st.session_state.get( 'image_temperature', 0.0, ) ),
			top_p=float( st.session_state.get( 'image_top_percent', 0.0, ) ),
			frequency=float( st.session_state.get( 'image_frequency_penalty', 0.0, ) ),
			presence=float( st.session_state.get( 'image_presence_penalty', 0.0, ) ),
			max_tokens=int( st.session_state.get( 'image_max_tokens', 0, ) ),
			media_resolution=str( st.session_state.get( 'image_media_resolution', '',
			) or '' ),
			instruct=str( st.session_state.get( 'image_system_instructions', '', ) or '' ),
			grounded=bool( st.session_state.get( 'image_grounded', False, ) ),
			image_search=bool( st.session_state.get( 'image_image_search', False, ) ), )

	if provider_name == 'Grok':
		return image.edit( prompt=prompt, model=model, path=path, image_url='',
			aspect_ratio=str( st.session_state.get( 'image_aspect_ratio', 'auto',
			) or 'auto' ),
			number=int( st.session_state.get( 'image_number', 1, ) ), )

	raise ValueError( f'Unsupported Images provider: {provider_name}' )

get_audio_help

get_audio_help(name: str, fallback: str = '') -> str

Get audio help.

Purpose

Returns normalized information for the application component. The method provides a stable view of provider capabilities, stored state, or response metadata so UI controls and downstream logic can consume it consistently.

Parameters:

Name Type Description Default
name str

Name value used by the operation.

required
fallback str

Fallback value used by the operation.

''

Returns:

Name Type Description
str str

Return value produced by the operation.

Source code in app.py
def get_audio_help( name: str, fallback: str = '' ) -> str:
	"""Get audio help.

	Purpose:
	    Returns normalized information for the application component. The method provides a
	    stable view of provider capabilities, stored state, or response metadata so UI
	    controls and
	    downstream logic can consume it consistently.

	Args:
	    name (str): Name value used by the operation.
	    fallback (str): Fallback value used by the operation.

	Returns:
	    str: Return value produced by the operation."""
	return str( getattr( cfg, name, fallback ) or fallback )

get_audio_options

get_audio_options(
    instance: Any,
    attr_name: str,
    fallback: Optional[List[Any]] = None,
) -> List[Any]

Get audio options.

Purpose

Returns normalized information for the application component. The method provides a stable view of provider capabilities, stored state, or response metadata so UI controls and downstream logic can consume it consistently.

Parameters:

Name Type Description Default
instance Any

Instance value used by the operation.

required
attr_name str

Attr name value used by the operation.

required
fallback Optional[List[Any]]

Fallback value used by the operation.

None

Returns:

Type Description
List[Any]

List[Any]: Return value produced by the operation.

Source code in app.py
def get_audio_options( instance: Any, attr_name: str,
	fallback: Optional[ List[ Any ] ] = None ) -> List[ Any ]:
	"""Get audio options.

	Purpose:
	    Returns normalized information for the application component. The method provides a
	    stable view of provider capabilities, stored state, or response metadata so UI
	    controls and
	    downstream logic can consume it consistently.

	Args:
	    instance (Any): Instance value used by the operation.
	    attr_name (str): Attr name value used by the operation.
	    fallback (Optional[List[Any]]): Fallback value used by the operation.

	Returns:
	    List[Any]: Return value produced by the operation."""
	values = getattr( instance, attr_name, None )
	if callable( values ):
		try:
			values = values( )
		except Exception:
			values = None

	if values is None:
		values = fallback or [ ]

	if isinstance( values, tuple ):
		values = list( values )

	if isinstance( values, list ):
		return values

	return fallback or [ ]

audio_has_method

audio_has_method(
    instance: Any, method_names: List[str]
) -> bool

Audio has method.

Purpose

Performs the audio_has_method workflow using the inputs supplied by the caller and the current runtime configuration. The function keeps this behavior isolated so related UI, provider, and data-processing paths can call it consistently.

Parameters:

Name Type Description Default
instance Any

Instance value used by the operation.

required
method_names List[str]

Method names value used by the operation.

required

Returns:

Name Type Description
bool bool

Return value produced by the operation.

Source code in app.py
def audio_has_method( instance: Any, method_names: List[ str ] ) -> bool:
	"""Audio has method.

	Purpose:
	    Performs the audio_has_method workflow using the inputs supplied by the caller and the
	    current runtime configuration. The function keeps this behavior isolated so related UI,
	    provider, and data-processing paths can call it consistently.

	Args:
	    instance (Any): Instance value used by the operation.
	    method_names (List[str]): Method names value used by the operation.

	Returns:
	    bool: Return value produced by the operation."""
	for method_name in method_names:
		method = getattr( instance, method_name, None )
		if callable( method ):
			return True

	return False

get_audio_task_options

get_audio_task_options() -> List[str]

Get audio task options.

Purpose

Returns normalized information for the application component. The method provides a stable view of provider capabilities, stored state, or response metadata so UI controls and downstream logic can consume it consistently.

Returns:

Type Description
List[str]

List[str]: Return value produced by the operation.

Source code in app.py
def get_audio_task_options( ) -> List[ str ]:
	"""Get audio task options.

	Purpose:
	    Returns normalized information for the application component. The method provides a
	    stable view of provider capabilities, stored state, or response metadata so UI
	    controls and
	    downstream logic can consume it consistently.

	Returns:
	    List[str]: Return value produced by the operation."""
	tasks: List[ str ] = [ ]

	if audio_has_method( transcriber, [ 'transcribe', 'create_transcription', 'create' ] ):
		tasks.append( 'Transcribe' )

	if audio_has_method( translator, [ 'translate', 'create_translation', 'create' ] ):
		tasks.append( 'Translate' )

	if audio_has_method( tts, [ 'create_speech', 'synthesize', 'generate', 'create' ] ):
		tasks.append( 'Text-to-Speech' )

	return tasks

get_audio_task_instance

get_audio_task_instance(task: Optional[str]) -> Any

Get audio task instance.

Purpose

Returns normalized information for the application component. The method provides a stable view of provider capabilities, stored state, or response metadata so UI controls and downstream logic can consume it consistently.

Parameters:

Name Type Description Default
task Optional[str]

Task value used by the operation.

required

Returns:

Name Type Description
Any Any

Return value produced by the operation.

Source code in app.py
def get_audio_task_instance( task: Optional[ str ] ) -> Any:
	"""Get audio task instance.

	Purpose:
	    Returns normalized information for the application component. The method provides a
	    stable view of provider capabilities, stored state, or response metadata so UI
	    controls and
	    downstream logic can consume it consistently.

	Args:
	    task (Optional[str]): Task value used by the operation.

	Returns:
	    Any: Return value produced by the operation."""
	if task == 'Translate':
		return translator

	if task == 'Text-to-Speech':
		return tts

	return transcriber

get_audio_model_options

get_audio_model_options(task: Optional[str]) -> List[str]

Get audio model options.

Purpose

Returns normalized information for the application component. The method provides a stable view of provider capabilities, stored state, or response metadata so UI controls and downstream logic can consume it consistently.

Parameters:

Name Type Description Default
task Optional[str]

Task value used by the operation.

required

Returns:

Type Description
List[str]

List[str]: Return value produced by the operation.

Source code in app.py
def get_audio_model_options( task: Optional[ str ] ) -> List[ str ]:
	"""Get audio model options.

	Purpose:
	    Returns normalized information for the application component. The method provides a
	    stable view of provider capabilities, stored state, or response metadata so UI controls
	    and downstream logic can consume it consistently.

	Args:
	    task (Optional[str]): Task value used by the operation.

	Returns:
	    List[str]: Return value produced by the operation."""
	instance = get_audio_task_instance( task )
	options = get_audio_options( instance, 'model_options' )

	if not options:
		model_value = getattr( instance, 'model', '' )
		options = [ model_value ] if model_value else [ ]

	return [ str( option ) for option in options if str( option ).strip( ) ]

get_audio_language_options

get_audio_language_options(
    task: Optional[str],
) -> List[str]

Get audio language options.

Purpose

Returns normalized information for the application component. The method provides a stable view of provider capabilities, stored state, or response metadata so UI controls and downstream logic can consume it consistently.

Parameters:

Name Type Description Default
task Optional[str]

Task value used by the operation.

required

Returns:

Type Description
List[str]

List[str]: Return value produced by the operation.

Source code in app.py
def get_audio_language_options( task: Optional[ str ] ) -> List[ str ]:
	"""Get audio language options.

	Purpose:
	    Returns normalized information for the application component. The method provides a
	    stable view of provider capabilities, stored state, or response metadata so UI
	    controls and
	    downstream logic can consume it consistently.

	Args:
	    task (Optional[str]): Task value used by the operation.

	Returns:
	    List[str]: Return value produced by the operation.
	"""
	instance = get_audio_task_instance( task )
	options = get_audio_options( instance, 'language_options' )

	if not options:
		options = [ 'auto', 'en', 'Spanish', 'French', 'German', 'Italian', 'Japanese' ]

	return [ str( option ) for option in options if str( option ).strip( ) ]

get_audio_voice_options

get_audio_voice_options() -> List[str]

Get audio voice options.

Purpose

Returns normalized information for the application component. The method provides a stable view of provider capabilities, stored state, or response metadata so UI controls and downstream logic can consume it consistently.

Returns:

Type Description
List[str]

List[str]: Return value produced by the operation.

Source code in app.py
def get_audio_voice_options( ) -> List[ str ]:
	"""Get audio voice options.

	Purpose:
	    Returns normalized information for the application component. The method provides a
	    stable view of provider capabilities, stored state, or response metadata so UI
	    controls and downstream logic
	    can consume it consistently.

	Returns:
	    List[str]: Return value produced by the operation.
	"""
	options = get_audio_options( tts, 'voice_options' )
	if not options:
		options = [ getattr( tts, 'voice', '' ) ]

	return [ str( option ) for option in options if str( option ).strip( ) ]

get_audio_format_options

get_audio_format_options(task: Optional[str]) -> List[Any]

Get audio format options.

Purpose

Returns normalized information for the application component. The method provides a stable view of provider capabilities, stored state, or response metadata so UI controls and downstream logic can consume it consistently.

Parameters:

Name Type Description Default
task Optional[str]

Task value used by the operation.

required

Returns:

Type Description
List[Any]

List[Any]: Return value produced by the operation.

Source code in app.py
def get_audio_format_options( task: Optional[ str ] ) -> List[ Any ]:
	"""Get audio format options.

	Purpose:
	    Returns normalized information for the application component. The method provides a
	    stable view of provider capabilities, stored state, or response metadata so UI controls
	    and downstream logic can consume it consistently.

	Args:
	    task (Optional[str]): Task value used by the operation.

	Returns:
	    List[Any]: Return value produced by the operation.
	"""
	instance = get_audio_task_instance( task )

	if task == 'Text-to-Speech':
		options = get_audio_options( instance, 'format_options' )
		if not options:
			options = get_audio_options( instance, 'response_format_options' )
		if not options:
			options = get_audio_options( instance, 'output_format_options' )
		if not options:
			options = [ 'mp3', 'wav' ]

		return options

	options = get_audio_options( instance, 'response_format_options' )
	if not options:
		options = get_audio_options( instance, 'format_options' )
	if not options:
		options = [ 'text', 'json' ]

	return options

get_audio_include_options

get_audio_include_options(task: Optional[str]) -> List[str]

Get audio include options.

Purpose

Returns normalized information for the application component. The method provides a stable view of provider capabilities, stored state, or response metadata so UI controls and down stream logic can consume it consistently.

Parameters:

Name Type Description Default
task Optional[str]

Task value used by the operation.

required

Returns:

Type Description
List[str]

List[str]: Return value produced by the operation.

Source code in app.py
def get_audio_include_options( task: Optional[ str ] ) -> List[ str ]:
	"""Get audio include options.

	Purpose:
	    Returns normalized information for the application component. The method provides a
	    stable view of provider capabilities, stored state, or response metadata so UI controls
	    and down stream logic can consume it consistently.

	Args:
	    task (Optional[str]): Task value used by the operation.

	Returns:
	    List[str]: Return value produced by the operation.
	"""
	instance = get_audio_task_instance( task )
	options = get_audio_options( instance, 'include_options' )
	return [ str( option ) for option in options if str( option ).strip( ) ]

get_audio_sample_rate_options

get_audio_sample_rate_options() -> List[int]

Get audio sample rate options.

Purpose

Returns normalized information for the application component. The method provides a stable view of provider capabilities, stored state, or response metadata so UI controls and downstream logic can consume it consistently.

Returns:

Type Description
List[int]

List[int]: Return value produced by the operation.

Source code in app.py
def get_audio_sample_rate_options( ) -> List[ int ]:
	"""Get audio sample rate options.

	Purpose:
	    Returns normalized information for the application component. The method provides a
	    stable view of provider capabilities, stored state, or response metadata so UI
	    controls and  downstream logic can consume it consistently.

	Returns:
	    List[int]: Return value produced by the operation.
	"""
	options = get_audio_options( tts, 'sample_rate_options' )
	if not options:
		options = [ 0, 8000, 16000, 22050, 24000, 44100, 48000 ]

	values: List[ int ] = [ 0 ]
	for option in options:
		try:
			value = int( option )
			if value not in values:
				values.append( value )
		except Exception:
			continue

	return values

get_audio_bit_rate_options

get_audio_bit_rate_options() -> List[int]

Get audio bit rate options.

Purpose

Returns normalized information for the application component. The method provides a stable view of provider capabilities, stored state, or response metadata so UI controls and downstream logic can consume it consistently.

Returns:

Type Description
List[int]

List[int]: Return value produced by the operation.

Source code in app.py
def get_audio_bit_rate_options( ) -> List[ int ]:
	"""Get audio bit rate options.

	Purpose:
	    Returns normalized information for the application component. The method provides a
	    stable view of provider capabilities, stored state, or response metadata so UI
	    controls and downstream logic can consume it consistently.

	Returns:
	    List[int]: Return value produced by the operation.
	"""
	options = get_audio_options( tts, 'bit_rate_options' )
	if not options:
		options = [ 0, 32000, 64000, 96000, 128000, 192000 ]

	values: List[ int ] = [ 0 ]
	for option in options:
		try:
			value = int( option )
			if value not in values:
				values.append( value )
		except Exception:
			continue

	return values

sanitize_audio_selection

sanitize_audio_selection(
    key: str, valid_options: List[Any], default: Any = ""
) -> None

Sanitize audio selection.

Purpose

Performs the sanitize_audio_selection workflow using the inputs supplied by the caller and the current runtime configuration. The function keeps this behavior isolated so related UI, provider, and data-processing paths can call it consistently.

Parameters:

Name Type Description Default
key str

Key value used by the operation.

required
valid_options List[Any]

Valid options value used by the operation.

required
default Any

Default value used by the operation.

''

Returns:

Name Type Description
None None

This function performs its work through side effects and does not return a value.

Source code in app.py
def sanitize_audio_selection( key: str, valid_options: List[ Any ], default: Any='' ) -> None:
	"""Sanitize audio selection.

	Purpose:
	    Performs the sanitize_audio_selection workflow using the inputs supplied by the caller
	    and the current runtime configuration. The function keeps this behavior isolated so
	    related UI,
	    provider, and data-processing paths can call it consistently.

	Args:
	    key (str): Key value used by the operation.
	    valid_options (List[Any]): Valid options value used by the operation.
	    default (Any): Default value used by the operation.

	Returns:
	    None: This function performs its work through side effects and does not return a
	        value."""
	current_value = st.session_state.get( key, default )

	if current_value in [ None, '' ]:
		return

	if valid_options and current_value not in valid_options:
		st.session_state[ key ] = default

sanitize_audio_multiselect

sanitize_audio_multiselect(
    key: str, valid_options: List[str]
) -> None

Sanitize audio multiselect.

Purpose

Performs the sanitize_audio_multiselect workflow using the inputs supplied by the caller and the current runtime configuration. The function keeps this behavior isolated so related UI, provider, and data-processing paths can call it consistently.

Parameters:

Name Type Description Default
key str

Key value used by the operation.

required
valid_options List[str]

Valid options value used by the operation.

required

Returns:

Name Type Description
None None

This function performs its work through side effects and does not return a value.

Source code in app.py
def sanitize_audio_multiselect( key: str, valid_options: List[ str ] ) -> None:
	"""Sanitize audio multiselect.

	Purpose:
	    Performs the sanitize_audio_multiselect workflow using the inputs supplied by the
	    caller and the current runtime configuration. The function keeps this behavior
	    isolated so related UI,
	    provider, and data-processing paths can call it consistently.

	Args:
	    key (str): Key value used by the operation.
	    valid_options (List[str]): Valid options value used by the operation.

	Returns:
	    None: This function performs its work through side effects and does not return a
	        value.
	"""
	current_values = st.session_state.get( key, [ ] )

	if not isinstance( current_values, list ):
		st.session_state[ key ] = [ ]
		return

	st.session_state[ key ] = [ item for item in current_values if item in valid_options ]

parse_audio_domains

parse_audio_domains(value: Any) -> List[str]

Parse audio domains.

Purpose

Performs the parse_audio_domains workflow using the inputs supplied by the caller and the current runtime configuration. The function keeps this behavior isolated so related UI, provider, and data-processing paths can call it consistently.

Parameters:

Name Type Description Default
value Any

Value value used by the operation.

required

Returns:

Type Description
List[str]

List[str]: Return value produced by the operation.

Source code in app.py
def parse_audio_domains( value: Any ) -> List[ str ]:
	"""Parse audio domains.

	Purpose:
	    Performs the parse_audio_domains workflow using the inputs supplied by the caller and
	    the current runtime configuration. The function keeps this behavior isolated so
	    related UI,
	    provider, and data-processing paths can call it consistently.

	Args:
	    value (Any): Value value used by the operation.

	Returns:
	    List[str]: Return value produced by the operation."""
	raw = str( value or '' )
	return [ item.strip( ) for item in raw.split( ',' ) if item.strip( ) ]

save_audio_upload

save_audio_upload(uploaded_file: Any) -> Optional[str]

Save audio upload.

Purpose

Persists or stages input data so it can be used by later provider or application workflows. The function standardizes file handling and returns a stable reference for downstream processing.

Parameters:

Name Type Description Default
uploaded_file Any

Uploaded file value used by the operation.

required

Returns:

Type Description
Optional[str]

Optional[str]: Return value produced by the operation.

Source code in app.py
def save_audio_upload( uploaded_file: Any ) -> Optional[ str ]:
	"""Save audio upload.

	Purpose:
	    Persists or stages input data so it can be used by later provider or application
	    workflows. The function standardizes file handling and returns a stable reference
	    for downstream processing.

	Args:
	    uploaded_file (Any): Uploaded file value used by the operation.

	Returns:
	    Optional[str]: Return value produced by the operation."""
	if uploaded_file is None:
		return None

	if 'save_temp' in globals( ):
		try:
			return save_temp( uploaded_file )
		except Exception:
			pass

	try:
		name = getattr( uploaded_file, 'name', 'audio.wav' )
		_, ext = os.path.splitext( name )
		ext = ext or '.wav'

		with tempfile.NamedTemporaryFile( delete=False, suffix=ext ) as tmp:
			if hasattr( uploaded_file, 'getbuffer' ):
				tmp.write( uploaded_file.getbuffer( ) )
			elif hasattr( uploaded_file, 'getvalue' ):
				tmp.write( uploaded_file.getvalue( ) )
			elif hasattr( uploaded_file, 'read' ):
				tmp.write( uploaded_file.read( ) )
			else:
				return None

			return tmp.name
	except Exception:
		return None

append_audio_message

append_audio_message(role: str, content: str) -> None

Append audio message.

Purpose

Performs the append_audio_message workflow using the inputs supplied by the caller and the current runtime configuration. The function keeps this behavior isolated so related UI, provider, and data-processing paths can call it consistently.

Parameters:

Name Type Description Default
role str

Role value used by the operation.

required
content str

Content value used by the operation.

required

Returns:

Name Type Description
None None

This function performs its work through side effects and does not return a value.

Source code in app.py
def append_audio_message( role: str, content: str ) -> None:
	"""Append audio message.

	Purpose:
	    Performs the append_audio_message workflow using the inputs supplied by the caller and
	    the current runtime configuration. The function keeps this behavior isolated so
	    related UI,
	    provider, and data-processing paths can call it consistently.

	Args:
	    role (str): Role value used by the operation.
	    content (str): Content value used by the operation.

	Returns:
	    None: This function performs its work through side effects and does not return a
	        value.
	"""
	if not isinstance( st.session_state.get( 'audio_messages' ), list ):
		st.session_state[ 'audio_messages' ] = [ ]

	st.session_state[ 'audio_messages' ].append( { 'role': role, 'content': content, } )

render_audio_messages

render_audio_messages() -> None

Render audio messages.

Purpose

Renders the requested user interface element or result block in Streamlit using normalized inputs. The function keeps presentation logic isolated from provider calls and data-processing steps so the screen output remains predictable.

Returns:

Name Type Description
None None

This function performs its work through side effects and does not return a value.

Source code in app.py
def render_audio_messages( ) -> None:
	"""Render audio messages.

	Purpose:
	    Renders the requested user interface element or result block in Streamlit using
	    normalized inputs. The function keeps presentation logic isolated from provider calls
	    and
	    data-processing steps so the screen output remains predictable.

	Returns:
	    None: This function performs its work through side effects and does not return a
			value.
	"""
	if not isinstance( st.session_state.get( 'audio_messages' ), list ):
		st.session_state[ 'audio_messages' ] = [ ]

	for msg in st.session_state.get( 'audio_messages', [ ] ):
		if not isinstance( msg, dict ):
			continue

		with st.chat_message( msg.get( 'role', 'assistant' ), avatar='' ):
			st.markdown( msg.get( 'content', '' ) )

clear_audio_messages

clear_audio_messages() -> None

Clear audio messages.

Purpose

Removes or resets the requested application state or provider resource in a controlled manner. The function keeps cleanup behavior centralized so callers do not duplicate lifecycle logic.

Returns:

Name Type Description
None None

This function performs its work through side effects and does not return a value.

Source code in app.py
def clear_audio_messages( ) -> None:
	"""Clear audio messages.

	Purpose:
	    Removes or resets the requested application state or provider resource in a controlled
	    manner. The function keeps cleanup behavior centralized so callers do not duplicate
	    lifecycle
	    logic.

	Returns:
	    None: This function performs its work through side effects and does not return a
	        value.
	"""
	st.session_state[ 'audio_messages' ] = [ ]
	st.session_state[ 'audio_output' ] = ''
	st.session_state[ 'audio_output_bytes' ] = None
	st.session_state[ 'audio_output_path' ] = ''
	st.session_state[ 'audio_last_result' ] = { }
	st.session_state[ 'audio_last_usage' ] = { }

clear_audio_instructions

clear_audio_instructions() -> None

Clear audio instructions.

Purpose

Removes or resets the requested application state or provider resource in a controlled manner. The function keeps cleanup behavior centralized so callers do not duplicate lifecycle logic.

Returns:

Name Type Description
None None

This function performs its work through side effects and does not return a value.

Source code in app.py
def clear_audio_instructions( ) -> None:
	"""Clear audio instructions.

	Purpose:
	    Removes or resets the requested application state or provider resource in a controlled
	    manner. The function keeps cleanup behavior centralized so callers do not duplicate
	    lifecycle
	    logic.

	Returns:
	    None: This function performs its work through side effects and does not return a
	        value.
	"""
	st.session_state[ 'audio_system_instructions' ] = ''
	st.session_state[ 'instructions' ] = ''

convert_audio_system_instructions

convert_audio_system_instructions() -> None

Convert audio system instructions.

Purpose

Performs the convert_audio_system_instructions workflow using the inputs supplied by the caller and the current runtime configuration. The function keeps this behavior isolated so related UI, provider, and data-processing paths can call it consistently.

Returns:

Name Type Description
None None

This function performs its work through side effects and does not return a value.

Source code in app.py
def convert_audio_system_instructions( ) -> None:
	"""Convert audio system instructions.

	Purpose:
	    Performs the convert_audio_system_instructions workflow using the inputs supplied by
	    the caller and the current runtime configuration. The function keeps this behavior
	    isolated so
	    related UI,  provider, and data-processing paths can call it consistently.

	Returns:
	    None: This function performs its work through side effects and does not return a
	        value.
	"""
	text_value = st.session_state.get( 'audio_system_instructions', '' )
	if not isinstance( text_value, str ) or not text_value.strip( ):
		return

	source = text_value.strip( )
	if cfg.XML_BLOCK_PATTERN.search( source ):
		converted = convert_xml( source )
	else:
		converted = convert_markdown( source )

	st.session_state[ 'audio_system_instructions' ] = converted

load_audio_instruction_template

load_audio_instruction_template() -> None

Load audio instruction template.

Purpose

Loads the selected Audio-mode prompt template into the Audio-mode system-instruction field using the stable prompt identifier stored in session state.

Returns:

Name Type Description
None None

This function performs its work through side effects and does not return a value.

Raises:

Type Description
Exception

Re-raises exceptions after recording them with the application logger.

Source code in app.py
def load_audio_instruction_template( ) -> None:
	"""Load audio instruction template.

	Purpose:
	    Loads the selected Audio-mode prompt template into the Audio-mode system-instruction
	    field using the stable prompt identifier stored in session state.

	Returns:
	    None: This function performs its work through side effects and does not return a value.

	Raises:
	    Exception: Re-raises exceptions after recording them with the application logger.
	"""
	try:
		load_prompt_template( prompt_id_key='audio_prompt_id',
			instructions_key='audio_system_instructions', )
	except Exception as e:
		ex = Error( e )
		ex.module = 'app'
		ex.cause = 'Audio Mode'
		ex.method = 'load_audio_instruction_template( ) -> None'
		Logger( ).write( ex )
		raise ex

reset_audio_task_controls

reset_audio_task_controls() -> None

Reset audio task controls.

Purpose

Removes or resets the requested application state or provider resource in a controlled manner. The function keeps cleanup behavior centralized so callers do not duplicate lifecycle logic.

Returns:

Name Type Description
None None

This function performs its work through side effects and does not return a value.

Source code in app.py
def reset_audio_task_controls( ) -> None:
	"""Reset audio task controls.

	Purpose:
	    Removes or resets the requested application state or provider resource in a controlled
	    manner.
	    The function keeps cleanup behavior centralized so callers do not duplicate lifecycle
	    logic.

	Returns:
	    None: This function performs its work through side effects and does not return a
		value.
	"""
	for key in [ 'audio_task', 'audio_model', 'audio_language', 'audio_voice', 'audio_format',
		'audio_response_format', 'audio_speed', 'audio_sample_rate', 'audio_bit_rate', ]:
		if key in st.session_state:
			del st.session_state[ key ]

reset_audio_inference_controls

reset_audio_inference_controls() -> None

Reset audio inference controls.

Purpose

Removes or resets the requested application state or provider resource in a controlled manner. The function keeps cleanup behavior centralized so callers do not duplicate lifecycle logic.

Returns:

Name Type Description
None None

This function performs its work through side effects and does not return a value.

Source code in app.py
def reset_audio_inference_controls( ) -> None:
	"""Reset audio inference controls.

	Purpose:
	    Removes or resets the requested application state or provider resource in a controlled
	    manner. The function keeps cleanup behavior centralized so callers do not duplicate
	    lifecycle
	    logic.

	Returns:
	    None: This function performs its work through side effects and does not return a
	        value.
	"""
	for key in [ 'audio_temperature', 'audio_top_percent', 'audio_top_k',
		'audio_frequency_penalty', 'audio_presence_penalty', 'audio_presense_penalty',
		'audio_max_tokens', 'audio_include', 'audio_stream', 'audio_store',
		'audio_background', ]:
		if key in st.session_state:
			del st.session_state[ key ]

reset_audio_playback_controls

reset_audio_playback_controls() -> None

Reset audio playback controls.

Purpose

Removes or resets the requested application state or provider resource in a controlled manner. The function keeps cleanup behavior centralized so callers do not duplicate lifecycle logic.

Returns:

Name Type Description
None None

This function performs its work through side effects and does not return a value.

Source code in app.py
def reset_audio_playback_controls( ) -> None:
	"""Reset audio playback controls.

	Purpose:
	    Removes or resets the requested application state or provider resource in a controlled
	    manner. The function keeps cleanup behavior centralized so callers do not duplicate
	    lifecycle logic.

	Returns:
	    None: This function performs its work through side effects and does not return a
	        value."""
	for key in [ 'audio_start_time', 'audio_end_time', 'audio_loop', 'audio_autoplay',
		'audio_output_bytes', 'audio_output_path', 'audio_upload_path',
		'audio_recorded_path', ]:
		if key in st.session_state:
			del st.session_state[ key ]

update_audio_usage

update_audio_usage(instance: Any) -> None

Update audio usage.

Purpose

Performs the update_audio_usage workflow using the inputs supplied by the caller and the current runtime configuration. The function keeps this behavior isolated so related UI, provider, and data-processing paths can call it consistently.

Parameters:

Name Type Description Default
instance Any

Instance value used by the operation.

required

Returns:

Name Type Description
None None

This function performs its work through side effects and does not return a value.

Source code in app.py
def update_audio_usage( instance: Any ) -> None:
	"""Update audio usage.

	Purpose:
	    Performs the update_audio_usage workflow using the inputs supplied by the caller and
	    the current runtime configuration. The function keeps this behavior isolated so
	    related UI,
	    provider, and data-processing paths can call it consistently.

	Args:
	    instance (Any): Instance value used by the operation.

	Returns:
	    None: This function performs its work through side effects and does not return a value.
	"""
	try:
		response = getattr( instance, 'response', None )
		usage = getattr( response, 'usage', None )

		if usage is None and hasattr( instance, 'get_usage' ):
			usage = instance.get_usage( )

		if usage is None:
			st.session_state[ 'audio_last_usage' ] = { }
			return

		if hasattr( usage, 'model_dump' ):
			st.session_state[ 'audio_last_usage' ] = usage.model_dump( )
		elif isinstance( usage, dict ):
			st.session_state[ 'audio_last_usage' ] = usage
		else:
			st.session_state[ 'audio_last_usage' ] = { 'usage': str( usage ) }

		if 'update_token_counters' in globals( ):
			update_token_counters( response )
	except Exception:
		st.session_state[ 'audio_last_usage' ] = { }

normalize_audio_text_result

normalize_audio_text_result(result: Any) -> str

Normalize audio text result.

Purpose

Normalizes provider transcription and translation results into displayable text.

Parameters:

Name Type Description Default
result Any

Provider result returned by the active audio wrapper.

required

Returns:

Name Type Description
str str

Extracted text or an empty string.

Source code in app.py
def normalize_audio_text_result( result: Any ) -> str:
	"""Normalize audio text result.

	Purpose:
	    Normalizes provider transcription and translation results into displayable text.

	Args:
	    result (Any): Provider result returned by the active audio wrapper.

	Returns:
	    str: Extracted text or an empty string.
	"""
	if result is None:
		return ''

	if isinstance( result, str ):
		return result.strip( )

	if isinstance( result, dict ):
		for key in [ 'text', 'transcript', 'translation', 'content', 'output_text' ]:
			value = result.get( key )
			if isinstance( value, str ) and value.strip( ):
				return value.strip( )

		return str( result )

	for attr_name in [ 'text', 'transcript', 'translation', 'content', 'output_text' ]:
		value = getattr( result, attr_name, None )
		if isinstance( value, str ) and value.strip( ):
			return value.strip( )

	return str( result ).strip( )

normalize_audio_bytes_result

normalize_audio_bytes_result(
    result: Any,
) -> Optional[bytes]

Normalize audio bytes result.

Purpose

Normalizes provider text-to-speech results into audio bytes.

Parameters:

Name Type Description Default
result Any

Provider result returned by the active text-to-speech wrapper.

required

Returns:

Type Description
Optional[bytes]

Optional[bytes]: Generated audio bytes when available; otherwise None.

Source code in app.py
def normalize_audio_bytes_result( result: Any ) -> Optional[ bytes ]:
	"""Normalize audio bytes result.

	Purpose:
	    Normalizes provider text-to-speech results into audio bytes.

	Args:
	    result (Any): Provider result returned by the active text-to-speech wrapper.

	Returns:
	    Optional[bytes]: Generated audio bytes when available; otherwise None.
	"""
	if result is None:
		return None

	if isinstance( result, bytes ):
		return result

	if isinstance( result, bytearray ):
		return bytes( result )

	if isinstance( result, dict ):
		for key in [ 'audio_bytes', 'bytes', 'content', 'data', 'audio' ]:
			value = result.get( key )
			if isinstance( value, bytes ):
				return value

			if isinstance( value, bytearray ):
				return bytes( value )

	for attr_name in [ 'audio_bytes', 'bytes', 'content', 'data', 'audio' ]:
		value = getattr( result, attr_name, None )
		if isinstance( value, bytes ):
			return value

		if isinstance( value, bytearray ):
			return bytes( value )

	return None

get_audio_mime_type

get_audio_mime_type(format_value: Any) -> str

Get audio MIME type.

Purpose

Converts the selected provider audio format into a valid MIME type for Streamlit playback and download controls.

Parameters:

Name Type Description Default
format_value Any

Provider audio format or MIME-type value.

required

Returns:

Name Type Description
str str

Valid audio MIME type.

Source code in app.py
def get_audio_mime_type( format_value: Any ) -> str:
	"""Get audio MIME type.

	Purpose:
	    Converts the selected provider audio format into a valid MIME type for Streamlit
	    playback and download controls.

	Args:
	    format_value (Any): Provider audio format or MIME-type value.

	Returns:
	    str: Valid audio MIME type.
	"""
	format_text = str( format_value or '' ).strip( ).lower( )

	if not format_text:
		return 'audio/mpeg'

	if format_text.startswith( 'audio/' ):
		return format_text

	mime_map = { 'mp3': 'audio/mpeg', 'mpeg': 'audio/mpeg', 'mpga': 'audio/mpeg',
		'wav': 'audio/wav', 'pcm': 'audio/pcm', 'opus': 'audio/opus', 'ogg': 'audio/ogg',
		'flac': 'audio/flac', 'aac': 'audio/aac', 'm4a': 'audio/mp4', 'mp4': 'audio/mp4',
		'webm': 'audio/webm', 'mulaw': 'audio/basic', 'alaw': 'audio/basic', }

	return mime_map.get( format_text, f'audio/{format_text}' )

get_audio_file_extension

get_audio_file_extension(format_value: Any) -> str

Get audio file extension.

Purpose

Converts the selected provider audio format into a safe download-file extension.

Parameters:

Name Type Description Default
format_value Any

Provider audio format or MIME-type value.

required

Returns:

Name Type Description
str str

Audio file extension without a leading period.

Source code in app.py
def get_audio_file_extension( format_value: Any ) -> str:
	"""Get audio file extension.

	Purpose:
	    Converts the selected provider audio format into a safe download-file extension.

	Args:
	    format_value (Any): Provider audio format or MIME-type value.

	Returns:
	    str: Audio file extension without a leading period.
	"""
	format_text = str( format_value or '' ).strip( ).lower( )

	if '/' in format_text:
		format_text = format_text.rsplit( '/', 1 )[ -1 ]

	extension_map = { 'mpeg': 'mp3', 'x-wav': 'wav', 'wave': 'wav', 'basic': 'au', }

	return extension_map.get( format_text, format_text or 'mp3' )

get_audio_source_mime_type

get_audio_source_mime_type(
    path: str, selected_format: Any
) -> str

Get audio source MIME type.

Purpose

Resolves the source-audio MIME type required by Gemini and Grok upload workflows.

Parameters:

Name Type Description Default
path str

Local source-audio path.

required
selected_format Any

Current format selection from Audio Mode.

required

Returns:

Name Type Description
str str

Source-audio MIME type.

Source code in app.py
def get_audio_source_mime_type( path: str, selected_format: Any ) -> str:
	"""Get audio source MIME type.

	Purpose:
	    Resolves the source-audio MIME type required by Gemini and Grok upload workflows.

	Args:
	    path (str): Local source-audio path.
	    selected_format (Any): Current format selection from Audio Mode.

	Returns:
	    str: Source-audio MIME type.
	"""
	selected_text = str( selected_format or '' ).strip( ).lower( )

	if selected_text.startswith( 'audio/' ):
		return selected_text

	suffix = Path( path ).suffix.lower( )
	mime_map = { '.mp3': 'audio/mpeg', '.mpeg': 'audio/mpeg', '.mpga': 'audio/mpeg',
		'.wav': 'audio/wav', '.flac': 'audio/flac', '.ogg': 'audio/ogg', '.webm': 'audio/webm',
		'.mp4': 'audio/mp4', '.m4a': 'audio/m4a', '.aac': 'audio/aac', '.aiff': 'audio/aiff', }

	return mime_map.get( suffix, get_audio_mime_type( selected_text ) )

get_audio_target_language

get_audio_target_language() -> str

Get audio target language.

Purpose

Returns the selected target language required by provider translation wrappers.

Returns:

Name Type Description
str str

Selected target language.

Source code in app.py
def get_audio_target_language( ) -> str:
	"""Get audio target language.

	Purpose:
	    Returns the selected target language required by provider translation wrappers.

	Returns:
	    str: Selected target language.
	"""
	return str( st.session_state.get( 'audio_language', '' ) or '' ).strip( )

run_audio_transcription

run_audio_transcription(
    path: str, prompt: Optional[str] = None
) -> str

Run audio transcription.

Purpose

Executes the selected provider transcription wrapper using only arguments implemented by that provider contract.

Parameters:

Name Type Description Default
path str

Required local source-audio path.

required
prompt Optional[str]

Optional transcription guidance.

None

Returns:

Name Type Description
str str

Generated transcript.

Raises:

Type Description
Exception

Re-raises exceptions after recording them with the application logger.

Source code in app.py
def run_audio_transcription( path: str, prompt: Optional[ str ] = None ) -> str:
	"""Run audio transcription.

	Purpose:
	    Executes the selected provider transcription wrapper using only arguments implemented
	    by that provider contract.

	Args:
	    path (str): Required local source-audio path.
	    prompt (Optional[str]): Optional transcription guidance.

	Returns:
	    str: Generated transcript.

	Raises:
	    Exception: Re-raises exceptions after recording them with the application logger.
	"""
	try:
		throw_if( 'path', path )
		model = str( st.session_state.get( 'audio_model', '' ) or '' ).strip( )
		throw_if( 'model', model )
		language = str( st.session_state.get( 'audio_language', '' ) or '' ).strip( )
		response_format = st.session_state.get( 'audio_response_format' )
		prompt_text = str( prompt or '' )

		if provider_name == 'GPT':
			result = transcriber.transcribe( path=path, model=model, language=language,
				prompt=prompt_text, format=str( response_format or 'json' ),
				temperature=float( st.session_state.get( 'audio_temperature', 0.0 ) or 0.0 ),
				include=list( st.session_state.get( 'audio_include', [ ] ) or [ ] ), )

		elif provider_name == 'Gemini':
			result = transcriber.transcribe( path=path, model=model,
				language=language or 'Auto',
				mime_type=get_audio_source_mime_type( path, response_format ),
				temperature=float( st.session_state.get( 'audio_temperature', 0.0 ) or 0.0 ),
				top_p=float( st.session_state.get( 'audio_top_percent', 0.0 ) or 0.0 ),
				top_k=int( st.session_state.get( 'audio_top_k', 0 ) or 0 ), frequency=float(
					st.session_state.get( 'audio_frequency_penalty', 0.0 ) or 0.0 ),
				presence=float( st.session_state.get( 'audio_presence_penalty', 0.0 ) or 0.0 ),
				max_tokens=int( st.session_state.get( 'audio_max_tokens', 0 ) or 0 ),
				start_time=float( st.session_state.get( 'audio_start_time', 0.0 ) or 0.0 ),
				end_time=float( st.session_state.get( 'audio_end_time', 0.0 ) or 0.0 ),
				instruct=str( st.session_state.get( 'audio_system_instructions', '' ) or '' ),
				prompt=prompt_text, )

		elif provider_name == 'Grok':
			result = transcriber.transcribe( path=path, language=language,
				format=bool( response_format ),
				mime_type=get_audio_source_mime_type( path, '' ), keyterm=prompt_text, )

		else:
			raise ValueError( f'Unsupported Audio provider: {provider_name}' )

		text_result = normalize_audio_text_result( result )
		st.session_state[ 'audio_output' ] = text_result
		st.session_state[ 'audio_last_result' ] = { 'task': 'Transcribe',
			'provider': provider_name, 'model': model, 'text': text_result, }
		update_audio_usage( transcriber )
		return text_result
	except Exception as e:
		ex = Error( e )
		ex.module = 'app'
		ex.cause = 'Audio'
		ex.method = ('run_audio_transcription( path: str, '
		             'prompt: Optional[ str ] = None ) -> str')
		Logger( ).write( ex )
		raise ex

run_audio_translation

run_audio_translation(
    path: str, prompt: Optional[str] = None
) -> str

Run audio translation.

Purpose

Executes the selected provider audio-translation wrapper using only arguments implemented by that provider contract.

Parameters:

Name Type Description Default
path str

Required local source-audio path.

required
prompt Optional[str]

Optional translation guidance.

None

Returns:

Name Type Description
str str

Generated translated text.

Raises:

Type Description
Exception

Re-raises exceptions after recording them with the application logger.

Source code in app.py
def run_audio_translation( path: str, prompt: Optional[ str ] = None ) -> str:
	"""Run audio translation.

	Purpose:
	    Executes the selected provider audio-translation wrapper using only arguments
	    implemented by that provider contract.

	Args:
	    path (str): Required local source-audio path.
	    prompt (Optional[str]): Optional translation guidance.

	Returns:
	    str: Generated translated text.

	Raises:
	    Exception: Re-raises exceptions after recording them with the application logger.
	"""
	try:
		throw_if( 'path', path )
		model = str( st.session_state.get( 'audio_model', '' ) or '' ).strip( )
		throw_if( 'model', model )
		target_language = get_audio_target_language( )
		response_format = st.session_state.get( 'audio_response_format' )
		prompt_text = str( prompt or '' )

		if provider_name == 'GPT':
			result = translator.translate( path=path, model=model, prompt=prompt_text,
				format=str( response_format or 'json' ),
				temperature=float( st.session_state.get( 'audio_temperature', 0.0 ) or 0.0 ), )

		elif provider_name == 'Gemini':
			throw_if( 'audio_language', target_language )
			result = translator.translate( path=path, model=model, language=target_language,
				source='Auto', mime_type=get_audio_source_mime_type( path, response_format ),
				temperature=float( st.session_state.get( 'audio_temperature', 0.0 ) or 0.0 ),
				top_p=float( st.session_state.get( 'audio_top_percent', 0.0 ) or 0.0 ),
				top_k=int( st.session_state.get( 'audio_top_k', 0 ) or 0 ), frequency=float(
					st.session_state.get( 'audio_frequency_penalty', 0.0 ) or 0.0 ),
				presence=float( st.session_state.get( 'audio_presence_penalty', 0.0 ) or 0.0 ),
				max_tokens=int( st.session_state.get( 'audio_max_tokens', 0 ) or 0 ),
				start_time=float( st.session_state.get( 'audio_start_time', 0.0 ) or 0.0 ),
				end_time=float( st.session_state.get( 'audio_end_time', 0.0 ) or 0.0 ),
				instruct=str( st.session_state.get( 'audio_system_instructions', '' ) or '' ),
				prompt=prompt_text, )

		elif provider_name == 'Grok':
			throw_if( 'audio_language', target_language )
			result = translator.translate( path=path, target_language=target_language,
				model=model, source_language='', text_format=bool( response_format ),
				mime_type=get_audio_source_mime_type( path, '' ), keyterm=prompt_text,
				instruct=str( st.session_state.get( 'audio_system_instructions', '' ) or ''
				), )

		else:
			raise ValueError( f'Unsupported Audio provider: {provider_name}' )

		text_result = normalize_audio_text_result( result )
		st.session_state[ 'audio_output' ] = text_result
		st.session_state[ 'audio_last_result' ] = { 'task': 'Translate',
			'provider': provider_name, 'model': model,
			'target_language': target_language or 'English', 'text': text_result, }
		update_audio_usage( translator )
		return text_result
	except Exception as e:
		ex = Error( e )
		ex.module = 'app'
		ex.cause = 'Audio'
		ex.method = ('run_audio_translation( path: str, '
		             'prompt: Optional[ str ] = None ) -> str')
		Logger( ).write( ex )
		raise ex

run_audio_tts

run_audio_tts(text: str) -> Optional[bytes]

Run audio text-to-speech.

Purpose

Executes the selected provider text-to-speech wrapper using only arguments implemented by that provider contract.

Parameters:

Name Type Description Default
text str

Required text converted to speech.

required

Returns:

Type Description
Optional[bytes]

Optional[bytes]: Generated audio bytes when available.

Raises:

Type Description
Exception

Re-raises exceptions after recording them with the application logger.

Source code in app.py
def run_audio_tts( text: str ) -> Optional[ bytes ]:
	"""Run audio text-to-speech.

	Purpose:
	    Executes the selected provider text-to-speech wrapper using only arguments
	    implemented by that provider contract.

	Args:
	    text (str): Required text converted to speech.

	Returns:
	    Optional[bytes]: Generated audio bytes when available.

	Raises:
	    Exception: Re-raises exceptions after recording them with the application logger.
	"""
	try:
		throw_if( 'text', text )
		model = str( st.session_state.get( 'audio_model', '' ) or '' ).strip( )
		voice = str( st.session_state.get( 'audio_voice', '' ) or '' ).strip( )
		response_format = st.session_state.get( 'audio_response_format' )
		speed = float( st.session_state.get( 'audio_speed', 1.0 ) or 1.0 )
		output_path = str( st.session_state.get( 'audio_output_path', '' ) or '' )
		throw_if( 'voice', voice )

		if provider_name == 'GPT':
			throw_if( 'model', model )
			result = tts.create_speech( text=text, model=model,
				format=str( response_format or 'mp3' ), speed=speed, voice=voice,
				instruct=str( st.session_state.get( 'audio_system_instructions', '' ) or '' ),
				file_path=output_path, )

		elif provider_name == 'Gemini':
			throw_if( 'model', model )
			result = tts.create_speech( text=text, model=model,
				format=str( response_format or 'audio/wav' ), voice=voice, speed=speed,
				instruct=str( st.session_state.get( 'audio_system_instructions', '' ) or '' ),
				file_path=output_path,
				temperature=float( st.session_state.get( 'audio_temperature', 0.0 ) or 0.0 ),
				top_p=float( st.session_state.get( 'audio_top_percent', 0.0 ) or 0.0 ),
				max_tokens=int( st.session_state.get( 'audio_max_tokens', 0 ) or 0 ),
				sample_rate=int(
					st.session_state.get( 'audio_sample_rate', 24000 ) or 24000 ), )

		elif provider_name == 'Grok':
			result = tts.create_speech( text=text,
				language=str( st.session_state.get( 'audio_language', '' ) or 'auto' ),
				voice_id=voice, output_format=str( response_format or 'mp3' ), speed=speed,
				sample_rate=int( st.session_state.get( 'audio_sample_rate', 24000 ) or 24000 ),
				bit_rate=int( st.session_state.get( 'audio_bit_rate', 128000 ) or 128000 ),
				filepath=output_path, )

		else:
			raise ValueError( f'Unsupported Audio provider: {provider_name}' )

		audio_bytes = normalize_audio_bytes_result( result )
		st.session_state[ 'audio_output_bytes' ] = audio_bytes
		st.session_state[ 'audio_last_result' ] = { 'task': 'Text-to-Speech',
			'provider': provider_name, 'model': model, 'format': str( response_format or '' ),
			'bytes': len( audio_bytes ) if audio_bytes else 0, }
		update_audio_usage( tts )
		return audio_bytes
	except Exception as e:
		ex = Error( e )
		ex.module = 'app'
		ex.cause = 'Audio'
		ex.method = 'run_audio_tts( text: str ) -> Optional[ bytes ]'
		Logger( ).write( ex )
		raise ex

get_docqna_options

get_docqna_options(
    instance: Any,
    attr_name: str,
    fallback: Optional[List[Any]] = None,
) -> List[Any]

Get Document Q&A options.

Purpose

Returns provider-supported control options exposed by the active Chat wrapper.

Parameters:

Name Type Description Default
instance Any

Active provider Chat wrapper.

required
attr_name str

Wrapper option property or method name.

required
fallback Optional[List[Any]]

Values used when the wrapper exposes no options.

None

Returns:

Type Description
List[Any]

List[Any]: Provider-supported control options.

Source code in app.py
def get_docqna_options( instance: Any, attr_name: str,
	fallback: Optional[ List[ Any ] ] = None, ) -> List[ Any ]:
	"""Get Document Q&A options.

	Purpose:
	    Returns provider-supported control options exposed by the active Chat wrapper.

	Args:
	    instance (Any): Active provider Chat wrapper.
	    attr_name (str): Wrapper option property or method name.
	    fallback (Optional[List[Any]]): Values used when the wrapper exposes no options.

	Returns:
	    List[Any]: Provider-supported control options.
	"""
	values = getattr( instance, attr_name, None )

	if callable( values ):
		try:
			values = values( )
		except Exception:
			values = None

	if isinstance( values, tuple ):
		values = list( values )

	if isinstance( values, list ):
		return values

	return fallback or [ ]

sanitize_docqna_selection

sanitize_docqna_selection(
    key: str, options: List[Any], default: Any = ""
) -> None

Sanitize Document Q&A selection.

Purpose

Clears a stored single-selection value that is unsupported by the active provider.

Parameters:

Name Type Description Default
key str

Session-state key containing the selection.

required
options List[Any]

Provider-supported option values.

required
default Any

Replacement value used for an invalid selection.

''

Returns:

Name Type Description
None None

This function updates Streamlit session state.

Source code in app.py
def sanitize_docqna_selection( key: str, options: List[ Any ], default: Any = '', ) -> None:
	"""Sanitize Document Q&A selection.

	Purpose:
	    Clears a stored single-selection value that is unsupported by the active provider.

	Args:
	    key (str): Session-state key containing the selection.
	    options (List[Any]): Provider-supported option values.
	    default (Any): Replacement value used for an invalid selection.

	Returns:
	    None: This function updates Streamlit session state.
	"""
	value = st.session_state.get( key, default )

	if value in [ None, '' ]:
		return

	if value not in options:
		st.session_state[ key ] = default

sanitize_docqna_multiselect

sanitize_docqna_multiselect(
    key: str, options: List[Any]
) -> None

Sanitize Document Q&A multiselect.

Purpose

Removes stored multiselect values unsupported by the active provider.

Parameters:

Name Type Description Default
key str

Session-state key containing selected values.

required
options List[Any]

Provider-supported option values.

required

Returns:

Name Type Description
None None

This function updates Streamlit session state.

Source code in app.py
def sanitize_docqna_multiselect( key: str, options: List[ Any ], ) -> None:
	"""Sanitize Document Q&A multiselect.

	Purpose:
	    Removes stored multiselect values unsupported by the active provider.

	Args:
	    key (str): Session-state key containing selected values.
	    options (List[Any]): Provider-supported option values.

	Returns:
	    None: This function updates Streamlit session state.
	"""
	values = st.session_state.get( key, [ ] )

	if not isinstance( values, list ):
		st.session_state[ key ] = [ ]
		return

	st.session_state[ key ] = [ value for value in values if value in options ]

parse_docqna_list

parse_docqna_list(value: Any) -> List[str]

Parse Document Q&A list.

Purpose

Converts comma-delimited text or an existing sequence into normalized nonempty provider argument values.

Parameters:

Name Type Description Default
value Any

String or sequence containing provider option values.

required

Returns:

Type Description
List[str]

List[str]: Normalized provider argument values.

Source code in app.py
def parse_docqna_list( value: Any ) -> List[ str ]:
	"""Parse Document Q&A list.

	Purpose:
	    Converts comma-delimited text or an existing sequence into normalized nonempty
	    provider argument values.

	Args:
	    value (Any): String or sequence containing provider option values.

	Returns:
	    List[str]: Normalized provider argument values.
	"""
	if isinstance( value, str ):
		return [ item.strip( ) for item in value.split( ',' ) if item.strip( ) ]

	if isinstance( value, (list, tuple, set) ):
		return [ str( item ).strip( ) for item in value if str( item ).strip( ) ]

	return [ ]

clear_docqna_instructions

clear_docqna_instructions() -> None

Clear Document Q&A instructions.

Purpose

Clears the active Document Q&A system instructions and selected prompt template.

Returns:

Name Type Description
None None

This function updates Streamlit session state.

Source code in app.py
def clear_docqna_instructions( ) -> None:
	"""Clear Document Q&A instructions.

	Purpose:
	    Clears the active Document Q&A system instructions and selected prompt template.

	Returns:
	    None: This function updates Streamlit session state.
	"""
	st.session_state[ 'docqna_system_instructions' ] = ''
	st.session_state[ 'docqna_prompt_id' ] = None

convert_docqna_system_instructions

convert_docqna_system_instructions() -> None

Convert Document Q&A system instructions.

Purpose

Converts Document Q&A instructions between XML blocks and Markdown headings.

Returns:

Name Type Description
None None

This function updates Streamlit session state.

Source code in app.py
def convert_docqna_system_instructions( ) -> None:
	"""Convert Document Q&A system instructions.

	Purpose:
	    Converts Document Q&A instructions between XML blocks and Markdown headings.

	Returns:
	    None: This function updates Streamlit session state.
	"""
	instructions = str(
		st.session_state.get( 'docqna_system_instructions', '' ) or '' ).strip( )

	if not instructions:
		return

	if cfg.XML_BLOCK_PATTERN.search( instructions ):
		st.session_state[ 'docqna_system_instructions' ] = convert_xml( instructions )
	else:
		st.session_state[ 'docqna_system_instructions' ] = convert_markdown( instructions )

load_docqna_instruction_template

load_docqna_instruction_template() -> None

Load Document Q&A instruction template.

Purpose

Loads the selected Document Q&A prompt template into the system-instruction field.

Returns:

Name Type Description
None None

This function updates Streamlit session state.

Source code in app.py
def load_docqna_instruction_template( ) -> None:
	"""Load Document Q&A instruction template.

	Purpose:
	    Loads the selected Document Q&A prompt template into the system-instruction field.

	Returns:
	    None: This function updates Streamlit session state.
	"""
	load_prompt_template( prompt_id_key='docqna_prompt_id',
		instructions_key='docqna_system_instructions', )

unload_docqna_document

unload_docqna_document() -> None

Unload Document Q&A document.

Purpose

Removes the active local document and its bytes without clearing configuration, instructions, or conversation history.

Returns:

Name Type Description
None None

This function updates Streamlit session state.

Source code in app.py
def unload_docqna_document( ) -> None:
	"""Unload Document Q&A document.

	Purpose:
	    Removes the active local document and its bytes without clearing configuration,
	    instructions, or conversation history.

	Returns:
	    None: This function updates Streamlit session state.
	"""
	st.session_state[ 'docqna_uploaded' ] = None
	st.session_state[ 'docqna_file' ] = None
	st.session_state[ 'docqna_files' ] = [ ]
	st.session_state[ 'docqna_active_docs' ] = [ ]
	st.session_state[ 'doc_bytes' ] = { }
	st.session_state[ 'docqna_source' ] = ''

clear_docqna_messages

clear_docqna_messages() -> None

Clear Document Q&A messages.

Purpose

Clears Document Q&A conversation state and generated answer and source output.

Returns:

Name Type Description
None None

This function updates Streamlit session state.

Source code in app.py
def clear_docqna_messages( ) -> None:
	"""Clear Document Q&A messages.

	Purpose:
	    Clears Document Q&A conversation state and generated answer and source output.

	Returns:
	    None: This function updates Streamlit session state.
	"""
	st.session_state[ 'docqna_messages' ] = [ ]
	st.session_state[ 'docqna_history' ] = [ ]
	st.session_state[ 'docqna_answer' ] = ''
	st.session_state[ 'docqna_context' ] = [ ]
	st.session_state[ 'docqna_sources' ] = [ ]
	st.session_state[ 'last_answer' ] = ''
	st.session_state[ 'last_sources' ] = [ ]

run_document_query

run_document_query(prompt: str) -> str

Run Document Q&A query.

Purpose

Builds locally grounded document input and invokes the exact text-generation contract implemented by the selected provider Chat wrapper.

Parameters:

Name Type Description Default
prompt str

User question submitted for the active document.

required

Returns:

Name Type Description
str str

Provider-generated document-grounded answer.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in app.py
def run_document_query( prompt: str ) -> str:
	"""Run Document Q&A query.

	Purpose:
	    Builds locally grounded document input and invokes the exact text-generation contract
	    implemented by the selected provider Chat wrapper.

	Args:
	    prompt (str): User question submitted for the active document.

	Returns:
	    str: Provider-generated document-grounded answer.

	Raises:
	    Error: Re-raised after the exception is logged.
	"""
	try:
		throw_if( 'prompt', prompt )

		model = str( st.session_state.get( 'docqna_model', '' ) or '' ).strip( )
		throw_if( 'model', model )

		active_documents = st.session_state.get( 'docqna_active_docs', [ ], )

		if not active_documents:
			raise ValueError( 'Load a document before submitting a Document Q&A question.' )

		top_k = int( st.session_state.get( 'docqna_top_k', 0 ) or 0 )
		user_input = build_document_user_input( prompt, k=top_k or 6, )

		if not user_input:
			raise ValueError( 'The active document did not produce usable context.' )

		context = st.session_state.get( 'docqna_context', [ ], )
		instructions = str( st.session_state.get( 'docqna_system_instructions', '', ) or '' )
		temperature = float( st.session_state.get( 'docqna_temperature', 0.0, ) or 0.0 )
		top_p = float( st.session_state.get( 'docqna_top_percent', 0.0, ) or 0.0 )
		frequency = float( st.session_state.get( 'docqna_frequency_penalty', 0.0, ) or 0.0 )
		presence = float( st.session_state.get( 'docqna_presence_penalty', 0.0, ) or 0.0 )
		max_tokens = int( st.session_state.get( 'docqna_max_tokens', 0, ) or 0 )
		stream = bool( st.session_state.get( 'docqna_stream', False, ) )
		store = bool( st.session_state.get( 'docqna_store', False, ) )
		reasoning = str( st.session_state.get( 'docqna_reasoning', '', ) or '' )
		response_format = str( st.session_state.get( 'docqna_response_format', '', ) or '' )
		tools = list( st.session_state.get( 'docqna_tools', [ ], ) or [ ] )
		include = list( st.session_state.get( 'docqna_include', [ ], ) or [ ] )
		tool_choice = str( st.session_state.get( 'docqna_tool_choice', '', ) or '' )
		stops = parse_docqna_list( st.session_state.get( 'docqna_stops_input',
			st.session_state.get( 'docqna_stops', [ ], ), ) )

		if provider_name == 'GPT':
			answer = docqna.generate_text( prompt=user_input, model=model,
				temperature=temperature, format=response_format or None, top_p=top_p,
				frequency=frequency,
				max_tools=int( st.session_state.get( 'docqna_max_calls', 0, ) or 0 ),
				presence=presence, max_tokens=max_tokens, store=store, stream=stream,
				instruct=instructions,
				background=bool( st.session_state.get( 'docqna_background', False, ) ),
				reasoning=reasoning, include=include, tools=tools,
				allowed_domains=parse_docqna_list( st.session_state.get(
					'docqna_domains_input',
					st.session_state.get( 'docqna_domains', [ ], ), ) ),
				tool_choice=tool_choice,
				is_parallel=bool( st.session_state.get( 'docqna_parallel_tools', False, ) ),
				context=context, )

		elif provider_name == 'Gemini':
			answer = docqna.generate_text( prompt=user_input, model=model,
				number=max( 1, int( st.session_state.get( 'docqna_number', 1, ) or 1 ), ),
				temperature=temperature, top_p=top_p, top_k=top_k, frequency=frequency,
				presence=presence, max_tokens=max_tokens, stops=stops, instruct=instructions,
				response_format=response_format, tools=tools, tool_choice=tool_choice,
				reasoning=reasoning,
				modalities=list( st.session_state.get( 'docqna_modalities', [ ], ) or [ ] ),
				media_resolution=str(
					st.session_state.get( 'docqna_media_resolution', '', ) or '' ),
				context=context,
				content=str( st.session_state.get( 'docqna_content', '', ) or '' ),
				stream=stream, )

		elif provider_name == 'Grok':
			answer = docqna.generate_text( prompt=user_input, model=model,
				temperature=temperature, format=response_format or None, top_p=top_p,
				frequency=frequency, presence=presence, max_tokens=max_tokens, stops=stops,
				store=store, stream=stream, instruct=instructions, reasoning=reasoning,
				include=include, tools=tools, allowed_domains=parse_docqna_list(
					st.session_state.get( 'docqna_domains_input',
						st.session_state.get( 'docqna_domains', [ ], ), ) ),
				tool_choice=tool_choice,
				is_parallel=bool( st.session_state.get( 'docqna_parallel_tools', False, ) ),
				context=context,
				max_tools=int( st.session_state.get( 'docqna_max_calls', 0, ) or 0 ), )

		else:
			raise ValueError( f'Unsupported Document Q&A provider: {provider_name}' )

		if isinstance( answer, str ):
			output_text = answer.strip( )
		else:
			output_text = str(
				getattr( docqna, 'output_text', '' ) or getattr( answer, 'output_text',
					'' ) or answer or '' ).strip( )

		throw_if( 'output_text', output_text )

		st.session_state[ 'docqna_answer' ] = output_text
		st.session_state[ 'last_answer' ] = output_text

		if provider_name == 'Gemini':
			sources = [ ]
			get_sources = getattr( docqna, 'get_grounding_sources', None, )

			if callable( get_sources ):
				sources = get_sources( ) or [ ]

			st.session_state[ 'docqna_sources' ] = sources
			st.session_state[ 'last_sources' ] = sources

		usage_response = getattr( docqna, 'response', None )

		if usage_response is not None:
			update_token_counters( usage_response )

		return output_text
	except Exception as e:
		ex = Error( e )
		ex.module = 'app'
		ex.cause = 'Document Q&A'
		ex.method = 'run_document_query( prompt: str ) -> str'
		Logger( ).write( ex )
		raise ex

get_embedding_help

get_embedding_help(name: str, fallback: str = '') -> str

Get embedding help.

Purpose

Returns normalized help text for an Embeddings Mode control from the current application configuration.

Parameters:

Name Type Description Default
name str

Configuration attribute containing the help text.

required
fallback str

Fallback help text used when the attribute is unavailable.

''

Returns:

Name Type Description
str str

Configured or fallback help text.

Source code in app.py
def get_embedding_help( name: str, fallback: str = '' ) -> str:
	"""Get embedding help.

	Purpose:
	    Returns normalized help text for an Embeddings Mode control from the current
	    application configuration.

	Args:
	    name (str): Configuration attribute containing the help text.
	    fallback (str): Fallback help text used when the attribute is unavailable.

	Returns:
	    str: Configured or fallback help text.
	"""
	return str( getattr( cfg, name, fallback ) or fallback )

get_embedding_options

get_embedding_options(
    instance: Any,
    attr_name: str,
    fallback: Optional[List[Any]] = None,
) -> List[Any]

Get embedding options.

Purpose

Returns a normalized list of provider options exposed through an Embeddings wrapper property or method. Missing or explicitly unavailable options use the supplied fallback, while provider-wrapper execution failures are logged and re-raised.

Parameters:

Name Type Description Default
instance Any

Provider Embeddings wrapper instance.

required
attr_name str

Name of the wrapper option property or method. fallback (Optional[List[Any]]): Values used when the wrapper exposes no options.

required

Returns:

Type Description
List[Any]

List[Any]: Provider-supported option values or the supplied fallback.

Raises:

Type Description
Exception

Re-raises provider-wrapper failures after recording them with the application logger.

Source code in app.py
def get_embedding_options( instance: Any, attr_name: str,
	fallback: Optional[ List[ Any ] ] = None ) -> List[ Any ]:
	"""Get embedding options.

	Purpose:
	    Returns a normalized list of provider options exposed through an Embeddings wrapper
	    property or method. Missing or explicitly unavailable options use the supplied fallback,
	    while provider-wrapper execution failures are logged and re-raised.

	Args:
	    instance (Any): Provider Embeddings wrapper instance.
	    attr_name (str): Name of the wrapper option property or method.
	        fallback (Optional[List[Any]]): Values used when the wrapper exposes no options.

	Returns:
	    List[Any]: Provider-supported option values or the supplied fallback.

	Raises:
	    Exception: Re-raises provider-wrapper failures after recording them with the application
	        logger.
	"""
	try:
		throw_if( 'instance', instance )
		throw_if( 'attr_name', attr_name )

		default_values = list( fallback ) if fallback is not None else [ ]

		if not hasattr( instance, attr_name ):
			return default_values

		values = getattr( instance, attr_name )

		if callable( values ):
			values = values( )

		if values is None:
			return default_values

		if isinstance( values, list ):
			return values

		if isinstance( values, tuple ):
			return list( values )

		return default_values

	except Exception as e:
		ex = Error( e )
		ex.module = 'app'
		ex.cause = 'Embeddings'
		ex.method = (
			'get_embedding_options( instance: Any, attr_name: str, '
			'fallback: Optional[ List[ Any ] ] = None ) -> List[ Any ]'
		)
		Logger( ).write( ex )
		raise ex

normalize_embedding_text

normalize_embedding_text(value: Any) -> str

Normalize embedding text.

Purpose

Converts source input into normalized text suitable for chunking and provider embedding requests.

Parameters:

Name Type Description Default
value Any

Source text value.

required

Returns:

Name Type Description
str str

Normalized source text.

Source code in app.py
def normalize_embedding_text( value: Any ) -> str:
	"""Normalize embedding text.

	Purpose:
	    Converts source input into normalized text suitable for chunking and provider
	    embedding requests.

	Args:
	    value (Any): Source text value.

	Returns:
	    str: Normalized source text.
	"""
	if value is None:
		return ''

	return str( value ).replace( '\r\n', '\n' ).strip( )

chunk_embedding_text

chunk_embedding_text(
    text_value: str, chunk_size: int, overlap: int
) -> List[str]

Chunk embedding text.

Purpose

Divides embedding source text into bounded overlapping chunks while preserving the existing application chunking helpers when available.

Parameters:

Name Type Description Default
text_value str

Source text to divide.

required
chunk_size int

Maximum words or tokens retained in each chunk.

required
overlap int

Number of words or tokens shared by adjacent chunks.

required

Returns:

Type Description
List[str]

List[str]: Ordered embedding chunks.

Source code in app.py
def chunk_embedding_text( text_value: str, chunk_size: int, overlap: int ) -> List[ str ]:
	"""Chunk embedding text.

	Purpose:
	    Divides embedding source text into bounded overlapping chunks while preserving the
	    existing application chunking helpers when available.

	Args:
	    text_value (str): Source text to divide.
	    chunk_size (int): Maximum words or tokens retained in each chunk.
	    overlap (int): Number of words or tokens shared by adjacent chunks.

	Returns:
	    List[str]: Ordered embedding chunks.
	"""
	source = normalize_embedding_text( text_value )
	if not source:
		return [ ]

	if chunk_size <= 0:
		return [ source ]

	for helper_name in [ 'chunk_text', 'chunk_by_tokens', 'split_text' ]:
		helper = globals( ).get( helper_name )
		if callable( helper ):
			try:
				return helper( source, chunk_size, overlap )
			except TypeError:
				try:
					return helper( source, chunk_size=chunk_size, overlap=overlap )
				except Exception:
					pass
			except Exception:
				pass

	words = source.split( )
	if not words:
		return [ ]

	step = max( 1, chunk_size - max( 0, overlap ) )
	chunks = [ ]

	for index in range( 0, len( words ), step ):
		chunk = ' '.join( words[ index:index + chunk_size ] ).strip( )
		if chunk:
			chunks.append( chunk )

	return chunks

normalize_embedding_vectors

normalize_embedding_vectors(
    vectors: Any,
) -> List[List[float]]

Normalize embedding vectors.

Purpose

Converts GPT, Gemini, dictionary, response-object, batch, single-vector, and base64-encoded embedding outputs into a consistent collection of floating-point vectors.

Parameters:

Name Type Description Default
vectors Any

Provider embedding result or response object.

required

Returns:

Type Description
List[List[float]]

List[List[float]]: Normalized embedding vectors.

Source code in app.py
def normalize_embedding_vectors( vectors: Any ) -> List[ List[ float ] ]:
	"""Normalize embedding vectors.

	Purpose:
	    Converts GPT, Gemini, dictionary, response-object, batch, single-vector, and
	    base64-encoded embedding outputs into a consistent collection of floating-point
	    vectors.

	Args:
	    vectors (Any): Provider embedding result or response object.

	Returns:
	    List[List[float]]: Normalized embedding vectors.
	"""
	if vectors is None:
		return [ ]

	if isinstance( vectors, dict ):
		for key in [ 'data', 'embeddings', 'vectors', 'embedding' ]:
			if key in vectors:
				return normalize_embedding_vectors( vectors.get( key ) )

	if hasattr( vectors, 'data' ):
		return normalize_embedding_vectors( getattr( vectors, 'data' ) )

	if hasattr( vectors, 'embeddings' ):
		return normalize_embedding_vectors( getattr( vectors, 'embeddings' ) )

	if hasattr( vectors, 'embedding' ):
		return normalize_embedding_vectors( getattr( vectors, 'embedding' ) )

	if isinstance( vectors, str ):
		try:
			decoded = base64.b64decode( vectors )
			return [ np.frombuffer( decoded, dtype=np.float32, ).astype( float ).tolist( ) ]
		except Exception:
			return [ ]

	if isinstance( vectors, list ) and vectors:
		first = vectors[ 0 ]

		if isinstance( first, str ):
			rows = [ ]
			for item in vectors:
				rows.extend( normalize_embedding_vectors( item ) )

			return rows

		if isinstance( first, float ) or isinstance( first, int ):
			return [ [ float( value ) for value in vectors ] ]

		if isinstance( first, dict ):
			rows = [ ]
			for item in vectors:
				if 'embedding' in item:
					rows.extend( normalize_embedding_vectors( item.get( 'embedding' ) ) )
				elif 'vector' in item:
					rows.extend( normalize_embedding_vectors( item.get( 'vector' ) ) )

			return rows

		if hasattr( first, 'embedding' ):
			return [ [ float( value ) for value in getattr( item, 'embedding' ) ] for item in
				vectors if hasattr( item, 'embedding' ) ]

		if isinstance( first, list ):
			return [ [ float( value ) for value in row ] for row in vectors if
				isinstance( row, list ) ]

	return [ ]

call_embeddings_create

call_embeddings_create(chunks: List[str]) -> Any

Call embeddings create.

Purpose

Routes embedding creation to the exact GPT or Gemini wrapper contract using the currently selected provider controls.

Parameters:

Name Type Description Default
chunks List[str]

Required source-text chunks.

required

Returns:

Name Type Description
Any Any

Provider embedding output.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in app.py
def call_embeddings_create( chunks: List[ str ] ) -> Any:
	"""Call embeddings create.

	Purpose:
	    Routes embedding creation to the exact GPT or Gemini wrapper contract using the
	    currently selected provider controls.

	Args:
	    chunks (List[str]): Required source-text chunks.

	Returns:
	    Any: Provider embedding output.

	Raises:
	    Error: Re-raised after the exception is logged.
	"""
	try:
		throw_if( 'chunks', chunks )

		input_value = chunks if len( chunks ) != 1 else chunks[ 0 ]
		dimensions = st.session_state.get( 'embedding_dimensions',
			st.session_state.get( 'embeddings_dimensions', 0 ), )
		encoding_format = st.session_state.get( 'embedding_encoding_format',
			st.session_state.get( 'embeddings_encoding_format', '' ), )
		model = st.session_state.get( 'embedding_model' ) or None
		throw_if( 'model', model )
		if provider_name == 'GPT':
			return embedding.create( text=input_value, model=model,
				format=encoding_format or 'float',
				dimensions=(dimensions if int( dimensions or 0 ) > 0 else None), )

		if provider_name == 'Gemini':
			task_type = str( st.session_state.get( 'embedding_task_type', '' ) or '' )
			title = str( st.session_state.get( 'embedding_title', '' ) or '' )
			return embedding.create( text=input_value, model=model,
				dimensions=int( dimensions or 0 ), task_type=task_type, title=title, )

		raise ValueError( f'{provider_name} does not support embedding creation.' )
	except Exception as e:
		exception = Error( e )
		exception.module = 'app'
		exception.cause = 'Embeddings'
		exception.method = ('call_embeddings_create( chunks: List[ str ] ) -> Any')
		Logger( ).write( exception )
		raise exception

extract_embedding_usage

extract_embedding_usage(result: Any) -> Dict[str, Any]

Extract embedding usage.

Purpose

Extracts provider usage metadata from the active wrapper response or returned embedding result.

Parameters:

Name Type Description Default
result Any

Provider embedding result.

required

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Normalized provider usage metadata.

Source code in app.py
def extract_embedding_usage( result: Any ) -> Dict[ str, Any ]:
	"""Extract embedding usage.

	Purpose:
	    Extracts provider usage metadata from the active wrapper response or returned
	    embedding result.

	Args:
	    result (Any): Provider embedding result.

	Returns:
	    Dict[str, Any]: Normalized provider usage metadata.
	"""
	response = getattr( embedding, 'response', None ) or result

	if response is None:
		return { }

	usage = getattr( response, 'usage', None )
	if isinstance( usage, dict ):
		return usage

	if usage is not None:
		if hasattr( usage, 'model_dump' ):
			try:
				dumped_usage = usage.model_dump( )
				if isinstance( dumped_usage, dict ):
					return dumped_usage
			except Exception:
				pass

		try:
			return dict( usage )
		except Exception:
			return { 'usage': str( usage ) }

	if isinstance( response, dict ):
		response_usage = response.get( 'usage' )
		if isinstance( response_usage, dict ):
			return response_usage

	return { }

build_embedding_metrics

build_embedding_metrics(
    source_text: str,
    chunks: List[str],
    vectors: List[List[float]],
    usage: Dict[str, Any],
) -> Dict[str, Any]

Build embedding metrics.

Purpose

Builds source-text, chunk, vector, dimensionality, and usage metrics for the current embedding result.

Parameters:

Name Type Description Default
source_text str

Complete normalized source text.

required
chunks List[str]

Source-text chunks submitted to the provider.

required
vectors List[List[float]]

Normalized embedding vectors.

required
usage Dict[str, Any]

Provider usage metadata.

required

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Embedding metrics.

Source code in app.py
def build_embedding_metrics( source_text: str, chunks: List[ str ],
	vectors: List[ List[ float ] ], usage: Dict[ str, Any ] ) -> Dict[ str, Any ]:
	"""Build embedding metrics.

	Purpose:
	    Builds source-text, chunk, vector, dimensionality, and usage metrics for the
	    current embedding result.

	Args:
	    source_text (str): Complete normalized source text.
	    chunks (List[str]): Source-text chunks submitted to the provider.
	    vectors (List[List[float]]): Normalized embedding vectors.
	    usage (Dict[str, Any]): Provider usage metadata.

	Returns:
	    Dict[str, Any]: Embedding metrics.
	"""
	words = source_text.split( )
	total_words = len( words )
	unique_words = len( set( words ) )
	token_total = (count_tokens( source_text ) if 'count_tokens' in globals( ) else
	               total_words)
	dimensions = len( vectors[ 0 ] ) if vectors else 0

	return { 'tokens': token_total, 'words': total_words, 'unique_words': unique_words,
		'ttr': (unique_words / total_words if total_words > 0 else 0.0),
		'characters': len( source_text ), 'chunks': len( chunks ), 'vectors': len( vectors ),
		'dimensions': dimensions, 'usage': usage, }

build_embeddings_dataframe

build_embeddings_dataframe(
    chunks: List[str], vectors: List[List[float]]
) -> DataFrame

Build embeddings dataframe.

Purpose

Builds a tabular embedding output containing chunk identifiers, source text, and one column for each vector dimension.

Parameters:

Name Type Description Default
chunks List[str]

Source-text chunks.

required
vectors List[List[float]]

Normalized embedding vectors.

required

Returns:

Type Description
DataFrame

pd.DataFrame: Embedding output dataframe.

Source code in app.py
def build_embeddings_dataframe( chunks: List[ str ],
	vectors: List[ List[ float ] ] ) -> pd.DataFrame:
	"""Build embeddings dataframe.

	Purpose:
	    Builds a tabular embedding output containing chunk identifiers, source text, and
	    one column for each vector dimension.

	Args:
	    chunks (List[str]): Source-text chunks.
	    vectors (List[List[float]]): Normalized embedding vectors.

	Returns:
	    pd.DataFrame: Embedding output dataframe.
	"""
	if not vectors:
		return pd.DataFrame( )

	df_vectors = pd.DataFrame( vectors,
		columns=[ f'dim_{index}' for index in range( len( vectors[ 0 ] ) ) ], )

	df_vectors.insert( 0, 'ChunkIndex', range( 1, len( df_vectors ) + 1 ), )

	if chunks:
		df_vectors.insert( 1, 'Text', chunks[ :len( df_vectors ) ], )

	return df_vectors

render_embedding_metrics

render_embedding_metrics(metrics: Dict[str, Any]) -> None

Render embedding metrics.

Purpose

Renders token, chunk, vector, dimensionality, and type-token-ratio metrics for the active embedding result.

Parameters:

Name Type Description Default
metrics Dict[str, Any]

Embedding metrics.

required

Returns:

Name Type Description
None None

This function renders Streamlit controls.

Source code in app.py
def render_embedding_metrics( metrics: Dict[ str, Any ] ) -> None:
	"""Render embedding metrics.

	Purpose:
	    Renders token, chunk, vector, dimensionality, and type-token-ratio metrics for the
	    active embedding result.

	Args:
	    metrics (Dict[str, Any]): Embedding metrics.

	Returns:
	    None: This function renders Streamlit controls.
	"""
	col_m1, col_m2, col_m3, col_m4, col_m5 = st.columns( 5, border=True, )
	col_m1.metric( 'Tokens', metrics.get( 'tokens', 0 ) )
	col_m2.metric( 'Chunks', metrics.get( 'chunks', 0 ) )
	col_m3.metric( 'Vectors', metrics.get( 'vectors', 0 ) )
	col_m4.metric( 'Dimensions', metrics.get( 'dimensions', 0 ) )
	col_m5.metric( 'TTR', f"{float( metrics.get( 'ttr', 0.0 ) ):.3f}", )

reset_embeddings_all

reset_embeddings_all() -> None

Reset embeddings all.

Purpose

Clears Embeddings Mode source input, provider configuration, generated vectors, metrics, dataframe output, and compatibility aliases.

Returns:

Name Type Description
None None

This function updates Streamlit session state.

Source code in app.py
def reset_embeddings_all( ) -> None:
	"""Reset embeddings all.

	Purpose:
	    Clears Embeddings Mode source input, provider configuration, generated vectors,
	    metrics, dataframe output, and compatibility aliases.

	Returns:
	    None: This function updates Streamlit session state.
	"""
	keys_to_clear = [ 'embedding_input', 'embedding_text', 'embeddings_input_text',
		'embedding_file', 'embedding_file_uploader', 'embedding_model',
		'embedding_encoding_format', 'embedding_encoding_format_display',
		'embeddings_encoding_format', 'embedding_dimensions', 'embeddings_dimensions',
		'embedding_chunk_size', 'embeddings_chunk_size', 'embedding_chunk_overlap',
		'embeddings_overlap_amount', 'embedding_task_type', 'embedding_title',
		'embedding_chunks', 'embeddings_chunks', 'embedding_vectors', 'embeddings',
		'embedding_results', 'embedding_dataframe', 'embeddings_df', 'embedding_metrics',
		'embedding_usage', ]

	for key in keys_to_clear:
		if key in st.session_state:
			del st.session_state[ key ]

	st.session_state[ 'embedding_input' ] = ''
	st.session_state[ 'embedding_text' ] = ''
	st.session_state[ 'embeddings_input_text' ] = ''
	st.session_state[ 'embedding_file' ] = None
	st.session_state[ 'embedding_model' ] = ''
	st.session_state[ 'embedding_encoding_format' ] = ''
	st.session_state[ 'embeddings_encoding_format' ] = ''
	st.session_state[ 'embedding_dimensions' ] = 0
	st.session_state[ 'embeddings_dimensions' ] = 0
	st.session_state[ 'embedding_chunk_size' ] = 0
	st.session_state[ 'embeddings_chunk_size' ] = 0
	st.session_state[ 'embedding_chunk_overlap' ] = 0
	st.session_state[ 'embeddings_overlap_amount' ] = 0
	st.session_state[ 'embedding_task_type' ] = ''
	st.session_state[ 'embedding_title' ] = ''
	st.session_state[ 'embedding_chunks' ] = [ ]
	st.session_state[ 'embeddings_chunks' ] = [ ]
	st.session_state[ 'embedding_vectors' ] = [ ]
	st.session_state[ 'embeddings' ] = [ ]
	st.session_state[ 'embedding_results' ] = None
	st.session_state[ 'embedding_dataframe' ] = None
	st.session_state[ 'embeddings_df' ] = None
	st.session_state[ 'embedding_metrics' ] = { }
	st.session_state[ 'embedding_usage' ] = { }

update_embedding_usage

update_embedding_usage(response: Any) -> None

Update embedding usage.

Purpose

Updates the shared application token counters when the embedding provider exposes compatible usage metadata.

Parameters:

Name Type Description Default
response Any

Provider response containing usage metadata.

required

Returns:

Name Type Description
None None

This function updates Streamlit session state.

Source code in app.py
def update_embedding_usage( response: Any ) -> None:
	"""Update embedding usage.

	Purpose:
	    Updates the shared application token counters when the embedding provider exposes
	    compatible usage metadata.

	Args:
	    response (Any): Provider response containing usage metadata.

	Returns:
	    None: This function updates Streamlit session state.
	"""
	if response is None:
		return

	try:
		update_token_counters( response )
	except Exception:
		pass

get_files_help

get_files_help(name: str, fallback: str = '') -> str

Get Files help.

Purpose

Returns configured help text for a Files Mode control.

Parameters:

Name Type Description Default
name str

Configuration attribute name.

required
fallback str

Fallback text.

''

Returns:

Name Type Description
str str

Configured or fallback help text.

Source code in app.py
def get_files_help( name: str, fallback: str = '' ) -> str:
	"""Get Files help.

	Purpose:
	    Returns configured help text for a Files Mode control.

	Args:
	    name (str): Configuration attribute name.
	    fallback (str): Fallback text.

	Returns:
	    str: Configured or fallback help text.
	"""
	return str( getattr( cfg, name, fallback ) or fallback )

get_files_options

get_files_options(
    instance: Any,
    attr_name: str,
    fallback: Optional[List[Any]] = None,
) -> List[Any]

Get Files options.

Purpose

Returns provider-supported options exposed by a Files wrapper property or method.

Parameters:

Name Type Description Default
instance Any

Files wrapper instance.

required
attr_name str

Option property or method name.

required
fallback Optional[List[Any]]

Fallback options.

None

Returns:

Type Description
List[Any]

List[Any]: Provider-supported options.

Source code in app.py
def get_files_options( instance: Any, attr_name: str,
	fallback: Optional[ List[ Any ] ] = None ) -> List[ Any ]:
	"""Get Files options.

	Purpose:
	    Returns provider-supported options exposed by a Files wrapper property or method.

	Args:
	    instance (Any): Files wrapper instance.
	    attr_name (str): Option property or method name.
	    fallback (Optional[List[Any]]): Fallback options.

	Returns:
	    List[Any]: Provider-supported options.
	"""
	values = getattr( instance, attr_name, None )

	if callable( values ):
		try:
			values = values( )
		except Exception:
			values = None

	if isinstance( values, tuple ):
		values = list( values )

	if isinstance( values, list ):
		return values

	return fallback or [ ]

sanitize_files_selection

sanitize_files_selection(
    key: str, valid_options: List[Any], default: Any = ""
) -> None

Sanitize Files selection.

Purpose

Clears a stored selection when it is not supported by the active provider.

Parameters:

Name Type Description Default
key str

Session-state key.

required
valid_options List[Any]

Valid provider options.

required
default Any

Replacement value.

''

Returns:

Name Type Description
None None

This function updates session state.

Source code in app.py
def sanitize_files_selection( key: str, valid_options: List[ Any ], default: Any = '' ) -> None:
	"""Sanitize Files selection.

	Purpose:
	    Clears a stored selection when it is not supported by the active provider.

	Args:
	    key (str): Session-state key.
	    valid_options (List[Any]): Valid provider options.
	    default (Any): Replacement value.

	Returns:
	    None: This function updates session state.
	"""
	current_value = st.session_state.get( key, default )

	if current_value in [ None, '' ]:
		return

	if current_value not in valid_options:
		st.session_state[ key ] = default

sanitize_files_multiselect

sanitize_files_multiselect(
    key: str, valid_options: List[Any]
) -> None

Sanitize Files multiselect.

Purpose

Removes stored multiselect values unsupported by the active provider.

Parameters:

Name Type Description Default
key str

Session-state key.

required
valid_options List[Any]

Valid provider options.

required

Returns:

Name Type Description
None None

This function updates session state.

Source code in app.py
def sanitize_files_multiselect( key: str, valid_options: List[ Any ] ) -> None:
	"""Sanitize Files multiselect.

	Purpose:
	    Removes stored multiselect values unsupported by the active provider.

	Args:
	    key (str): Session-state key.
	    valid_options (List[Any]): Valid provider options.

	Returns:
	    None: This function updates session state.
	"""
	current_values = st.session_state.get( key, [ ] )

	if not isinstance( current_values, list ):
		st.session_state[ key ] = [ ]
		return

	st.session_state[ key ] = [ value for value in current_values if value in valid_options ]

normalize_file_id

normalize_file_id(result: Any) -> str

Normalize file identifier.

Purpose

Extracts a stable provider file identifier from a file response.

Parameters:

Name Type Description Default
result Any

Provider file response.

required

Returns:

Name Type Description
str str

Provider file identifier or resource name.

Source code in app.py
def normalize_file_id( result: Any ) -> str:
	"""Normalize file identifier.

	Purpose:
	    Extracts a stable provider file identifier from a file response.

	Args:
	    result (Any): Provider file response.

	Returns:
	    str: Provider file identifier or resource name.
	"""
	if result is None:
		return ''

	if isinstance( result, dict ):
		return str(
			result.get( 'id' ) or result.get( 'file_id' ) or result.get( 'name' ) or '' )

	return str(
		getattr( result, 'id', None ) or getattr( result, 'file_id', None ) or getattr( result,
			'name', None ) or '' )

normalize_files_list

normalize_files_list(result: Any) -> List[Dict[str, Any]]

Normalize Files list.

Purpose

Converts provider-specific file collections into rows for the Files Mode table.

Parameters:

Name Type Description Default
result Any

Provider file-list response.

required

Returns:

Type Description
List[Dict[str, Any]]

List[Dict[str, Any]]: Normalized file records.

Source code in app.py
def normalize_files_list( result: Any ) -> List[ Dict[ str, Any ] ]:
	"""Normalize Files list.

	Purpose:
	    Converts provider-specific file collections into rows for the Files Mode table.

	Args:
	    result (Any): Provider file-list response.

	Returns:
	    List[Dict[str, Any]]: Normalized file records.
	"""
	if result is None:
		return [ ]

	items = result

	if isinstance( result, dict ):
		items = (result.get( 'data' ) or result.get( 'files' ) or result.get( 'items' ) or [ ])

	if hasattr( result, 'data' ):
		items = getattr( result, 'data' )

	if hasattr( result, 'files' ):
		items = getattr( result, 'files' )

	if not isinstance( items, list ):
		try:
			items = list( items )
		except Exception:
			items = [ items ]

	rows: List[ Dict[ str, Any ] ] = [ ]

	for item in items:
		if item is None:
			continue

		if isinstance( item, dict ):
			file_id = (item.get( 'id' ) or item.get( 'file_id' ) or item.get( 'name' ))
			filename = (
					item.get( 'filename' ) or item.get( 'display_name' ) or item.get( 'name' ))
			purpose = (item.get( 'purpose' ) or item.get( 'mime_type' ) or item.get( 'state' ))
			created = (item.get( 'created_at' ) or item.get( 'create_time' ) or item.get(
				'created' ))
			size = (item.get( 'bytes' ) or item.get( 'size_bytes' ) or item.get( 'size' ))
		else:
			file_id = (
					getattr( item, 'id', None ) or getattr( item, 'file_id', None ) or getattr(
				item, 'name', None ))
			filename = (getattr( item, 'filename', None ) or getattr( item, 'display_name',
				None ) or getattr( item, 'name', None ))
			purpose = (getattr( item, 'purpose', None ) or getattr( item, 'mime_type',
				None ) or getattr( item, 'state', None ))
			created = (getattr( item, 'created_at', None ) or getattr( item, 'create_time',
				None ) or getattr( item, 'created', None ))
			size = (getattr( item, 'bytes', None ) or getattr( item, 'size_bytes',
				None ) or getattr( item, 'size', None ))

		rows.append( { 'id': str( file_id or '' ), 'filename': str( filename or '' ),
			'purpose': str( purpose or '' ), 'created': str( created or '' ),
			'size': str( size or '' ), } )

	return rows

normalize_file_metadata

normalize_file_metadata(result: Any) -> Dict[str, Any]

Normalize file metadata.

Purpose

Converts provider file metadata into a dictionary suitable for Streamlit output.

Parameters:

Name Type Description Default
result Any

Provider file response.

required

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Normalized metadata.

Source code in app.py
def normalize_file_metadata( result: Any ) -> Dict[ str, Any ]:
	"""Normalize file metadata.

	Purpose:
	    Converts provider file metadata into a dictionary suitable for Streamlit output.

	Args:
	    result (Any): Provider file response.

	Returns:
	    Dict[str, Any]: Normalized metadata.
	"""
	if result is None:
		return { }

	if isinstance( result, dict ):
		return result

	if hasattr( result, 'model_dump' ):
		try:
			value = result.model_dump( )
			if isinstance( value, dict ):
				return value
		except Exception:
			pass

	if hasattr( files, 'get_file_metadata' ):
		try:
			value = files.get_file_metadata( result )
			if isinstance( value, dict ):
				return value
		except Exception:
			pass

	return { 'result': str( result ) }

save_uploaded_file_for_api

save_uploaded_file_for_api(
    uploaded_file: Any,
) -> Optional[str]

Save uploaded file for API.

Purpose

Writes a Streamlit uploaded file to a temporary local path.

Parameters:

Name Type Description Default
uploaded_file Any

Streamlit uploaded-file object.

required

Returns:

Type Description
Optional[str]

Optional[str]: Temporary file path.

Source code in app.py
def save_uploaded_file_for_api( uploaded_file: Any ) -> Optional[ str ]:
	"""Save uploaded file for API.

	Purpose:
	    Writes a Streamlit uploaded file to a temporary local path.

	Args:
	    uploaded_file (Any): Streamlit uploaded-file object.

	Returns:
	    Optional[str]: Temporary file path.
	"""
	if uploaded_file is None:
		return None

	suffix = Path( getattr( uploaded_file, 'name', 'upload.bin' ) ).suffix or '.bin'

	with tempfile.NamedTemporaryFile( delete=False, suffix=suffix, ) as tmp:
		if hasattr( uploaded_file, 'getbuffer' ):
			tmp.write( uploaded_file.getbuffer( ) )
		elif hasattr( uploaded_file, 'getvalue' ):
			tmp.write( uploaded_file.getvalue( ) )
		elif hasattr( uploaded_file, 'read' ):
			tmp.write( uploaded_file.read( ) )
		else:
			return None

		return tmp.name

normalize_file_content

normalize_file_content(content: Any) -> str

Normalize file content.

Purpose

Converts extracted provider content into displayable text.

Parameters:

Name Type Description Default
content Any

Provider file content.

required

Returns:

Name Type Description
str str

Displayable content.

Source code in app.py
def normalize_file_content( content: Any ) -> str:
	"""Normalize file content.

	Purpose:
	    Converts extracted provider content into displayable text.

	Args:
	    content (Any): Provider file content.

	Returns:
	    str: Displayable content.
	"""
	if content is None:
		return ''

	if isinstance( content, str ):
		return content

	if isinstance( content, bytes ):
		try:
			return content.decode( 'utf-8' )
		except UnicodeDecodeError:
			return ''

	if isinstance( content, dict ):
		return json.dumps( content, indent=2, default=str )

	if hasattr( content, 'text' ):
		text_value = getattr( content, 'text', '' )
		if text_value:
			return str( text_value )

	return str( content )

get_effective_file_id

get_effective_file_id(*keys: str) -> str

Get effective file identifier.

Purpose

Returns the first populated provider file identifier from the supplied state keys.

Parameters:

Name Type Description Default
*keys str

Ordered session-state keys.

()

Returns:

Name Type Description
str str

Active file identifier.

Source code in app.py
def get_effective_file_id( *keys: str ) -> str:
	"""Get effective file identifier.

	Purpose:
	    Returns the first populated provider file identifier from the supplied state keys.

	Args:
	    *keys (str): Ordered session-state keys.

	Returns:
	    str: Active file identifier.
	"""
	for key in keys:
		value = st.session_state.get( key, '' )

		if isinstance( value, str ) and value.strip( ):
			return value.strip( )

	return ''

refresh_files_table

refresh_files_table() -> List[Dict[str, Any]]

Refresh Files table.

Purpose

Lists provider files and stores normalized records for display and selection.

Returns:

Type Description
List[Dict[str, Any]]

List[Dict[str, Any]]: Normalized provider file records.

Source code in app.py
def refresh_files_table( ) -> List[ Dict[ str, Any ] ]:
	"""Refresh Files table.

	Purpose:
	    Lists provider files and stores normalized records for display and selection.

	Returns:
	    List[Dict[str, Any]]: Normalized provider file records.
	"""
	if provider_name == 'GPT':
		result = files.list( purpose=st.session_state.get( 'files_purpose', '' ), )
	elif provider_name == 'Gemini':
		result = files.list( )
	elif provider_name == 'Grok':
		result = files.list( limit=int( st.session_state.get( 'files_limit', 100 ) or 100 ),
			pagination_token=str(
				st.session_state.get( 'files_pagination_token', '', ) or '' ), )
	else:
		raise ValueError( f'Unsupported Files provider: {provider_name}' )

	rows = normalize_files_list( result )
	st.session_state[ 'files_table' ] = rows

	if provider_name == 'Grok':
		st.session_state[ 'files_pagination_token' ] = str(
			getattr( files, 'next_token', '' ) or '' )

	return rows

upload_provider_file

upload_provider_file(
    uploaded_file: Any, purpose: Optional[str] = None
) -> Any

Upload provider file.

Purpose

Uploads a staged local file through the exact selected-provider Files contract.

Parameters:

Name Type Description Default
uploaded_file Any

Streamlit uploaded-file object.

required
purpose Optional[str]

Optional file-purpose value.

None

Returns:

Name Type Description
Any Any

Provider file response.

Source code in app.py
def upload_provider_file( uploaded_file: Any, purpose: Optional[ str ] = None ) -> Any:
	"""Upload provider file.

	Purpose:
	    Uploads a staged local file through the exact selected-provider Files contract.

	Args:
	    uploaded_file (Any): Streamlit uploaded-file object.
	    purpose (Optional[str]): Optional file-purpose value.

	Returns:
	    Any: Provider file response.
	"""
	path = save_uploaded_file_for_api( uploaded_file )

	if not path:
		raise ValueError( 'Could not create a temporary file for upload.' )

	filename = str( getattr( uploaded_file, 'name', '' ) or Path( path ).name )
	mime_type = str( getattr( uploaded_file, 'type', '' ) or '' )

	if provider_name == 'GPT':
		return files.upload( path=path, purpose=purpose or 'user_data', )

	if provider_name == 'Gemini':
		return files.upload( path=path, display_name=filename, mime_type=mime_type, )

	if provider_name == 'Grok':
		return files.upload( file_path=path, file_name=filename,
			purpose=purpose or 'assistants',
			expires_after=int( st.session_state.get( 'files_expires_after', 0, ) or 0 ), )

	raise ValueError( f'Unsupported Files provider: {provider_name}' )

retrieve_provider_file

retrieve_provider_file(file_id: str) -> Any

Retrieve provider file.

Purpose

Retrieves file metadata through the exact selected-provider Files contract.

Parameters:

Name Type Description Default
file_id str

Provider file identifier or resource name.

required

Returns:

Name Type Description
Any Any

Provider file metadata.

Source code in app.py
def retrieve_provider_file( file_id: str ) -> Any:
	"""Retrieve provider file.

	Purpose:
	    Retrieves file metadata through the exact selected-provider Files contract.

	Args:
	    file_id (str): Provider file identifier or resource name.

	Returns:
	    Any: Provider file metadata.
	"""
	throw_if( 'file_id', file_id )

	if provider_name == 'GPT':
		return files.retrieve( id=file_id )

	return files.retrieve( file_id=file_id )

extract_provider_file

extract_provider_file(file_id: str) -> Any

Extract provider file.

Purpose

Retrieves file content through the exact selected-provider Files contract.

Parameters:

Name Type Description Default
file_id str

Provider file identifier or resource name.

required

Returns:

Name Type Description
Any Any

Extracted content or downloaded bytes.

Source code in app.py
def extract_provider_file( file_id: str ) -> Any:
	"""Extract provider file.

	Purpose:
	    Retrieves file content through the exact selected-provider Files contract.

	Args:
	    file_id (str): Provider file identifier or resource name.

	Returns:
	    Any: Extracted content or downloaded bytes.
	"""
	throw_if( 'file_id', file_id )

	if provider_name == 'GPT':
		return files.extract( id=file_id )

	return files.extract( file_id=file_id )

delete_provider_file

delete_provider_file(file_id: str) -> Any

Delete provider file.

Purpose

Deletes a file through the exact selected-provider Files contract.

Parameters:

Name Type Description Default
file_id str

Provider file identifier or resource name.

required

Returns:

Name Type Description
Any Any

Provider deletion response.

Source code in app.py
def delete_provider_file( file_id: str ) -> Any:
	"""Delete provider file.

	Purpose:
	    Deletes a file through the exact selected-provider Files contract.

	Args:
	    file_id (str): Provider file identifier or resource name.

	Returns:
	    Any: Provider deletion response.
	"""
	throw_if( 'file_id', file_id )

	if provider_name == 'GPT':
		return files.delete( id=file_id )

	return files.delete( file_id=file_id )

ask_provider_file

ask_provider_file(file_id: str, prompt: str) -> str

Ask provider file.

Purpose

Executes a file-aware question through the exact search contract implemented by the selected provider wrapper.

Parameters:

Name Type Description Default
file_id str

Provider file identifier or resource name.

required
prompt str

Question asked about the file.

required

Returns:

Name Type Description
str str

Provider-generated answer.

Source code in app.py
def ask_provider_file( file_id: str, prompt: str ) -> str:
	"""Ask provider file.

	Purpose:
	    Executes a file-aware question through the exact search contract implemented by the
	    selected provider wrapper.

	Args:
	    file_id (str): Provider file identifier or resource name.
	    prompt (str): Question asked about the file.

	Returns:
	    str: Provider-generated answer.
	"""
	throw_if( 'file_id', file_id )
	throw_if( 'prompt', prompt )

	model = str( st.session_state.get( 'files_model', '' ) or '' )
	throw_if( 'model', model )

	if provider_name == 'GPT':
		result = files.search( id=file_id, query=prompt, model=model,
			max_chars=int( st.session_state.get( 'files_max_chars', 200000, ) or 200000 ), )
	elif provider_name == 'Gemini':
		result = files.search( prompt=prompt, file_id=file_id, model=model,
			temperature=float( st.session_state.get( 'files_temperature', 0.0, ) or 0.0 ),
			top_p=float( st.session_state.get( 'files_top_percent', 0.0, ) or 0.0 ), top_k=0,
			frequency=float( st.session_state.get( 'files_frequency_penalty', 0.0, ) or 0.0 ),
			presence=float( st.session_state.get( 'files_presence_penalty', 0.0, ) or 0.0 ),
			max_tokens=int( st.session_state.get( 'files_max_tokens', 0, ) or 0 ),
			instruct=str( st.session_state.get( 'files_system_instructions', '', ) or '' ),
			response_format=str( st.session_state.get( 'files_response_format', '', ) or ''
			), )
	elif provider_name == 'Grok':
		result = files.search( file_id=file_id, query=prompt, model=model,
			instruct=str( st.session_state.get( 'files_system_instructions', '', ) or '' ),
			temperature=float( st.session_state.get( 'files_temperature', 0.0, ) or 0.0 ),
			top_p=float( st.session_state.get( 'files_top_percent', 0.0, ) or 0.0 ),
			frequency=float( st.session_state.get( 'files_frequency_penalty', 0.0, ) or 0.0 ),
			presence=float( st.session_state.get( 'files_presence_penalty', 0.0, ) or 0.0 ),
			max_tokens=int( st.session_state.get( 'files_max_tokens', 0, ) or 0 ),
			store=bool( st.session_state.get( 'files_store', False, ) ),
			stream=bool( st.session_state.get( 'files_stream', False, ) ),
			include=list( st.session_state.get( 'files_include', [ ], ) or [ ] ),
			previous_id=str(
				st.session_state.get( 'files_previous_response_id', '', ) or '' ), )
	else:
		raise ValueError( f'Unsupported Files provider: {provider_name}' )

	if isinstance( result, str ):
		return result

	output_text = getattr( files, 'output_text', '' )

	if isinstance( output_text, str ) and output_text.strip( ):
		return output_text.strip( )

	return str( result or '' )

clear_files_outputs

clear_files_outputs() -> None

Clear Files outputs.

Purpose

Clears loaded file records, metadata, extracted content, and operation results.

Returns:

Name Type Description
None None

This function updates session state.

Source code in app.py
def clear_files_outputs( ) -> None:
	"""Clear Files outputs.

	Purpose:
	    Clears loaded file records, metadata, extracted content, and operation results.

	Returns:
	    None: This function updates session state.
	"""
	st.session_state[ 'files_table' ] = [ ]
	st.session_state[ 'files_metadata' ] = { }
	st.session_state[ 'files_delete_result' ] = { }
	st.session_state[ 'files_results' ] = None
	st.session_state[ 'files_content' ] = None
	st.session_state[ 'files_content_text' ] = ''

clear_files_messages

clear_files_messages() -> None

Clear Files messages.

Purpose

Clears Files Mode messages and the latest generated answer.

Returns:

Name Type Description
None None

This function updates session state.

Source code in app.py
def clear_files_messages( ) -> None:
	"""Clear Files messages.

	Purpose:
	    Clears Files Mode messages and the latest generated answer.

	Returns:
	    None: This function updates session state.
	"""
	st.session_state[ 'files_messages' ] = [ ]
	st.session_state[ 'files_last_answer' ] = ''

append_files_message

append_files_message(role: str, content: str) -> None

Append Files message.

Purpose

Adds a user or assistant message to Files Mode history.

Parameters:

Name Type Description Default
role str

Message role.

required
content str

Message content.

required

Returns:

Name Type Description
None None

This function updates session state.

Source code in app.py
def append_files_message( role: str, content: str ) -> None:
	"""Append Files message.

	Purpose:
	    Adds a user or assistant message to Files Mode history.

	Args:
	    role (str): Message role.
	    content (str): Message content.

	Returns:
	    None: This function updates session state.
	"""
	st.session_state[ 'files_messages' ].append( { 'role': role, 'content': content, } )

render_files_messages

render_files_messages() -> None

Render Files messages.

Purpose

Renders Files Mode conversation history.

Returns:

Name Type Description
None None

This function renders Streamlit output.

Source code in app.py
def render_files_messages( ) -> None:
	"""Render Files messages.

	Purpose:
	    Renders Files Mode conversation history.

	Returns:
	    None: This function renders Streamlit output.
	"""
	for message in st.session_state.get( 'files_messages', [ ], ):
		if not isinstance( message, dict ):
			continue

		with st.chat_message( message.get( 'role', 'assistant' ), ):
			st.markdown( message.get( 'content', '' ) )

clear_files_instructions

clear_files_instructions() -> None

Clear Files instructions.

Purpose

Clears Files Mode system instructions and its selected prompt template.

Returns:

Name Type Description
None None

This function updates session state.

Source code in app.py
def clear_files_instructions( ) -> None:
	"""Clear Files instructions.

	Purpose:
	    Clears Files Mode system instructions and its selected prompt template.

	Returns:
	    None: This function updates session state.
	"""
	st.session_state[ 'files_system_instructions' ] = ''
	st.session_state[ 'files_prompt_id' ] = None

convert_files_system_instructions

convert_files_system_instructions() -> None

Convert Files system instructions.

Purpose

Converts Files Mode instructions between XML blocks and Markdown headings.

Returns:

Name Type Description
None None

This function updates session state.

Source code in app.py
def convert_files_system_instructions( ) -> None:
	"""Convert Files system instructions.

	Purpose:
	    Converts Files Mode instructions between XML blocks and Markdown headings.

	Returns:
	    None: This function updates session state.
	"""
	text_value = st.session_state.get( 'files_system_instructions', '', )

	if not isinstance( text_value, str ):
		return

	if not text_value.strip( ):
		return

	source = text_value.strip( )

	if cfg.XML_BLOCK_PATTERN.search( source ):
		converted = convert_xml( source )
	else:
		converted = convert_markdown( source )

	st.session_state[ 'files_system_instructions' ] = converted

load_files_instruction_template

load_files_instruction_template() -> None

Load Files instruction template.

Purpose

Loads the selected Files Mode prompt template into the system-instruction field.

Returns:

Name Type Description
None None

This function updates session state.

Source code in app.py
def load_files_instruction_template( ) -> None:
	"""Load Files instruction template.

	Purpose:
	    Loads the selected Files Mode prompt template into the system-instruction field.

	Returns:
	    None: This function updates session state.
	"""
	load_prompt_template( prompt_id_key='files_prompt_id',
		instructions_key='files_system_instructions', )

get_vector_store_options

get_vector_store_options(
    instance: Any,
    attribute_name: str,
    fallback: Optional[List[Any]] = None,
) -> List[Any]

Get Vector Store options.

Purpose

Returns provider-supported option values exposed by the GPT VectorStores wrapper.

Parameters:

Name Type Description Default
instance Any

Active GPT VectorStores wrapper.

required
attribute_name str

Wrapper option-property name.

required
fallback Optional[List[Any]]

Values returned when the property is unavailable.

None

Returns:

Type Description
List[Any]

List[Any]: Provider-supported option values.

Source code in app.py
def get_vector_store_options( instance: Any, attribute_name: str,
	fallback: Optional[ List[ Any ] ] = None ) -> List[ Any ]:
	"""Get Vector Store options.

	Purpose:
	    Returns provider-supported option values exposed by the GPT VectorStores wrapper.

	Args:
	    instance (Any): Active GPT VectorStores wrapper.
	    attribute_name (str): Wrapper option-property name.
	    fallback (Optional[List[Any]]): Values returned when the property is unavailable.

	Returns:
	    List[Any]: Provider-supported option values.
	"""
	values = getattr( instance, attribute_name, None )

	if callable( values ):
		values = values( )

	if isinstance( values, tuple ):
		values = list( values )

	if isinstance( values, list ):
		return values

	return fallback or [ ]

parse_vector_store_json

parse_vector_store_json(
    value: Any, label: str
) -> Dict[str, Any]

Parse Vector Store JSON.

Purpose

Parses optional JSON text used by Vector Store metadata, attributes, filters, and ranking controls.

Parameters:

Name Type Description Default
value Any

JSON text or an existing dictionary.

required
label str

Field label included in validation errors.

required

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Parsed JSON object or an empty dictionary.

Raises:

Type Description
ValueError

Raised when nonempty input is not a JSON object.

Source code in app.py
def parse_vector_store_json( value: Any, label: str ) -> Dict[ str, Any ]:
	"""Parse Vector Store JSON.

	Purpose:
	    Parses optional JSON text used by Vector Store metadata, attributes, filters, and
	    ranking controls.

	Args:
	    value (Any): JSON text or an existing dictionary.
	    label (str): Field label included in validation errors.

	Returns:
	    Dict[str, Any]: Parsed JSON object or an empty dictionary.

	Raises:
	    ValueError: Raised when nonempty input is not a JSON object.
	"""
	if isinstance( value, dict ):
		return dict( value )

	raw_value = str( value or '' ).strip( )

	if not raw_value:
		return { }

	parsed_value = json.loads( raw_value )

	if not isinstance( parsed_value, dict ):
		raise ValueError( f'{label} must contain a JSON object.' )

	return parsed_value

parse_vector_store_ids

parse_vector_store_ids(value: Any) -> List[str]

Parse Vector Store identifiers.

Purpose

Converts comma-delimited file identifiers into unique nonempty values.

Parameters:

Name Type Description Default
value Any

Comma-delimited identifier text.

required

Returns:

Type Description
List[str]

List[str]: Unique parsed identifiers.

Source code in app.py
def parse_vector_store_ids( value: Any ) -> List[ str ]:
	"""Parse Vector Store identifiers.

	Purpose:
	    Converts comma-delimited file identifiers into unique nonempty values.

	Args:
	    value (Any): Comma-delimited identifier text.

	Returns:
	    List[str]: Unique parsed identifiers.
	"""
	identifiers: List[ str ] = [ ]

	for item in str( value or '' ).split( ',' ):
		identifier = item.strip( )

		if identifier and identifier not in identifiers:
			identifiers.append( identifier )

	return identifiers

get_selected_vector_store_id

get_selected_vector_store_id() -> str

Get selected Vector Store identifier.

Purpose

Returns the selected Vector Store identifier or the manually entered fallback.

Returns:

Name Type Description
str str

Active Vector Store identifier.

Source code in app.py
def get_selected_vector_store_id( ) -> str:
	"""Get selected Vector Store identifier.

	Purpose:
	    Returns the selected Vector Store identifier or the manually entered fallback.

	Returns:
	    str: Active Vector Store identifier.
	"""
	selected_id = str( st.session_state.get( 'stores_selected_id', '' ) or '' ).strip( )

	if selected_id:
		return selected_id

	return str( st.session_state.get( 'stores_manual_id', '' ) or '' ).strip( )

normalize_vector_store_rows

normalize_vector_store_rows(
    result: Any,
) -> List[Dict[str, Any]]

Normalize Vector Store rows.

Purpose

Converts a GPT Vector Store response into records suitable for Streamlit tables.

Parameters:

Name Type Description Default
result Any

Provider response containing one or more Vector Stores.

required

Returns:

Type Description
List[Dict[str, Any]]

List[Dict[str, Any]]: Normalized Vector Store records.

Source code in app.py
def normalize_vector_store_rows( result: Any ) -> List[ Dict[ str, Any ] ]:
	"""Normalize Vector Store rows.

	Purpose:
	    Converts a GPT Vector Store response into records suitable for Streamlit tables.

	Args:
	    result (Any): Provider response containing one or more Vector Stores.

	Returns:
	    List[Dict[str, Any]]: Normalized Vector Store records.
	"""
	raw_rows = getattr( result, 'data', result )

	if raw_rows is None:
		return [ ]

	if not isinstance( raw_rows, list ):
		raw_rows = [ raw_rows ]

	return [ normalize_storage_object( row ) for row in raw_rows ]

normalize_vector_file_rows

normalize_vector_file_rows(
    result: Any,
) -> List[Dict[str, Any]]

Normalize Vector Store file rows.

Purpose

Converts a GPT Vector Store file response into records suitable for Streamlit tables.

Parameters:

Name Type Description Default
result Any

Provider response containing one or more Vector Store files.

required

Returns:

Type Description
List[Dict[str, Any]]

List[Dict[str, Any]]: Normalized file records.

Source code in app.py
def normalize_vector_file_rows( result: Any ) -> List[ Dict[ str, Any ] ]:
	"""Normalize Vector Store file rows.

	Purpose:
	    Converts a GPT Vector Store file response into records suitable for Streamlit tables.

	Args:
	    result (Any): Provider response containing one or more Vector Store files.

	Returns:
	    List[Dict[str, Any]]: Normalized file records.
	"""
	raw_rows = getattr( result, 'data', result )

	if raw_rows is None:
		return [ ]

	if not isinstance( raw_rows, list ):
		raw_rows = [ raw_rows ]

	return [ normalize_storage_object( row ) for row in raw_rows ]

clear_vector_store_outputs

clear_vector_store_outputs() -> None

Clear Vector Store outputs.

Purpose

Clears Vector Store tables, metadata, batch results, and search results without changing configuration controls.

Returns:

Name Type Description
None None

This function updates Streamlit session state.

Source code in app.py
def clear_vector_store_outputs( ) -> None:
	"""Clear Vector Store outputs.

	Purpose:
	    Clears Vector Store tables, metadata, batch results, and search results without
	    changing configuration controls.

	Returns:
	    None: This function updates Streamlit session state.
	"""
	st.session_state[ 'stores_table' ] = [ ]
	st.session_state[ 'stores_files_table' ] = [ ]
	st.session_state[ 'stores_store_metadata' ] = { }
	st.session_state[ 'stores_batch_result' ] = { }
	st.session_state[ 'stores_search_results' ] = [ ]
	st.session_state[ 'stores_selected_id' ] = ''
	st.session_state[ 'stores_id' ] = ''

clear_vector_store_instructions

clear_vector_store_instructions() -> None

Clear Vector Store instructions.

Purpose

Clears Vector Store system instructions and the selected prompt template.

Returns:

Name Type Description
None None

This function updates Streamlit session state.

Source code in app.py
def clear_vector_store_instructions( ) -> None:
	"""Clear Vector Store instructions.

	Purpose:
	    Clears Vector Store system instructions and the selected prompt template.

	Returns:
	    None: This function updates Streamlit session state.
	"""
	st.session_state[ 'stores_system_instructions' ] = ''
	st.session_state[ 'stores_prompt_id' ] = None

load_vector_store_instruction_template

load_vector_store_instruction_template() -> None

Load Vector Store instruction template.

Purpose

Loads the selected prompt template into the Vector Store system-instruction field.

Returns:

Name Type Description
None None

This function updates Streamlit session state.

Source code in app.py
def load_vector_store_instruction_template( ) -> None:
	"""Load Vector Store instruction template.

	Purpose:
	    Loads the selected prompt template into the Vector Store system-instruction field.

	Returns:
	    None: This function updates Streamlit session state.
	"""
	load_prompt_template( prompt_id_key='stores_prompt_id',
		instructions_key='stores_system_instructions', )

convert_vector_store_instructions

convert_vector_store_instructions() -> None

Convert Vector Store instructions.

Purpose

Converts Vector Store system instructions between Markdown headings and XML-style heading elements.

Returns:

Name Type Description
None None

This function updates Streamlit session state.

Source code in app.py
def convert_vector_store_instructions( ) -> None:
	"""Convert Vector Store instructions.

	Purpose:
	    Converts Vector Store system instructions between Markdown headings and XML-style
	    heading elements.

	Returns:
	    None: This function updates Streamlit session state.
	"""
	instructions = str( st.session_state.get( 'stores_system_instructions', '' ) or '' )

	if instructions.strip( ):
		st.session_state[ 'stores_system_instructions' ] = convert_markdown( instructions )

get_collection_options

get_collection_options(
    instance: Any,
    attribute_name: str,
    fallback: Optional[List[Any]] = None,
) -> List[Any]

Get Collection options.

Purpose

Returns provider-supported option values exposed by the Grok Collections wrapper.

Parameters:

Name Type Description Default
instance Any

Active Grok Collections wrapper.

required
attribute_name str

Wrapper option-property name.

required
fallback Optional[List[Any]]

Values returned when the property is unavailable.

None

Returns:

Type Description
List[Any]

List[Any]: Provider-supported option values.

Source code in app.py
def get_collection_options( instance: Any, attribute_name: str,
	fallback: Optional[ List[ Any ] ] = None ) -> List[ Any ]:
	"""Get Collection options.

	Purpose:
	    Returns provider-supported option values exposed by the Grok Collections wrapper.

	Args:
	    instance (Any): Active Grok Collections wrapper.
	    attribute_name (str): Wrapper option-property name.
	    fallback (Optional[List[Any]]): Values returned when the property is unavailable.

	Returns:
	    List[Any]: Provider-supported option values.
	"""
	values = getattr( instance, attribute_name, None )

	if callable( values ):
		values = values( )

	if isinstance( values, tuple ):
		values = list( values )

	if isinstance( values, list ):
		return values

	return fallback or [ ]

parse_collection_json

parse_collection_json(
    value: Any, label: str
) -> Dict[str, Any]

Parse Collection JSON.

Purpose

Parses optional JSON used by Collection document attributes and search filters.

Parameters:

Name Type Description Default
value Any

JSON text or an existing dictionary.

required
label str

Field label included in validation errors.

required

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Parsed JSON object or an empty dictionary.

Raises:

Type Description
ValueError

Raised when nonempty input is not a JSON object.

Source code in app.py
def parse_collection_json( value: Any, label: str ) -> Dict[ str, Any ]:
	"""Parse Collection JSON.

	Purpose:
	    Parses optional JSON used by Collection document attributes and search filters.

	Args:
	    value (Any): JSON text or an existing dictionary.
	    label (str): Field label included in validation errors.

	Returns:
	    Dict[str, Any]: Parsed JSON object or an empty dictionary.

	Raises:
	    ValueError: Raised when nonempty input is not a JSON object.
	"""
	if isinstance( value, dict ):
		return dict( value )

	raw_value = str( value or '' ).strip( )

	if not raw_value:
		return { }

	parsed_value = json.loads( raw_value )

	if not isinstance( parsed_value, dict ):
		raise ValueError( f'{label} must contain a JSON object.' )

	return parsed_value

parse_collection_ids

parse_collection_ids(value: Any) -> List[str]

Parse Collection document identifiers.

Purpose

Converts comma-delimited document identifiers into unique nonempty values.

Parameters:

Name Type Description Default
value Any

Comma-delimited identifier text.

required

Returns:

Type Description
List[str]

List[str]: Unique parsed identifiers.

Source code in app.py
def parse_collection_ids( value: Any ) -> List[ str ]:
	"""Parse Collection document identifiers.

	Purpose:
	    Converts comma-delimited document identifiers into unique nonempty values.

	Args:
	    value (Any): Comma-delimited identifier text.

	Returns:
	    List[str]: Unique parsed identifiers.
	"""
	identifiers: List[ str ] = [ ]

	for item in str( value or '' ).split( ',' ):
		identifier = item.strip( )

		if identifier and identifier not in identifiers:
			identifiers.append( identifier )

	return identifiers

get_selected_collection_id

get_selected_collection_id() -> str

Get selected Collection identifier.

Purpose

Returns the selected Collection identifier or the manually entered fallback.

Returns:

Name Type Description
str str

Active Collection identifier.

Source code in app.py
def get_selected_collection_id( ) -> str:
	"""Get selected Collection identifier.

	Purpose:
	    Returns the selected Collection identifier or the manually entered fallback.

	Returns:
	    str: Active Collection identifier.
	"""
	selected_id = str( st.session_state.get( 'collections_selected_id', '' ) or '' ).strip( )

	if selected_id:
		return selected_id

	return str( st.session_state.get( 'collections_manual_id', '' ) or '' ).strip( )

normalize_collection_rows

normalize_collection_rows(
    result: Any,
) -> List[Dict[str, Any]]

Normalize Collection rows.

Purpose

Converts a Grok Collection response into records suitable for Streamlit tables.

Parameters:

Name Type Description Default
result Any

Provider response containing one or more Collections.

required

Returns:

Type Description
List[Dict[str, Any]]

List[Dict[str, Any]]: Normalized Collection records.

Source code in app.py
def normalize_collection_rows( result: Any ) -> List[ Dict[ str, Any ] ]:
	"""Normalize Collection rows.

	Purpose:
	    Converts a Grok Collection response into records suitable for Streamlit tables.

	Args:
	    result (Any): Provider response containing one or more Collections.

	Returns:
	    List[Dict[str, Any]]: Normalized Collection records.
	"""
	raw_rows = result

	if isinstance( raw_rows, dict ):
		raw_rows = (raw_rows.get( 'collections' ) or raw_rows.get( 'data' ) or raw_rows.get(
			'results' ) or raw_rows)

	if raw_rows is None:
		return [ ]

	if isinstance( raw_rows, dict ):
		raw_rows = [ raw_rows ]

	if not isinstance( raw_rows, list ):
		raw_rows = [ raw_rows ]

	return [ normalize_storage_object( row ) for row in raw_rows ]

normalize_collection_document_rows

normalize_collection_document_rows(
    result: Any,
) -> List[Dict[str, Any]]

Normalize Collection document rows.

Purpose

Converts a Grok Collection document response into records suitable for Streamlit tables.

Parameters:

Name Type Description Default
result Any

Provider response containing one or more Collection documents.

required

Returns:

Type Description
List[Dict[str, Any]]

List[Dict[str, Any]]: Normalized document records.

Source code in app.py
def normalize_collection_document_rows( result: Any ) -> List[ Dict[ str, Any ] ]:
	"""Normalize Collection document rows.

	Purpose:
	    Converts a Grok Collection document response into records suitable for Streamlit
	    tables.

	Args:
	    result (Any): Provider response containing one or more Collection documents.

	Returns:
	    List[Dict[str, Any]]: Normalized document records.
	"""
	raw_rows = result

	if isinstance( raw_rows, dict ):
		raw_rows = (raw_rows.get( 'documents' ) or raw_rows.get( 'data' ) or raw_rows.get(
			'results' ) or raw_rows)

	if raw_rows is None:
		return [ ]

	if isinstance( raw_rows, dict ):
		raw_rows = [ raw_rows ]

	if not isinstance( raw_rows, list ):
		raw_rows = [ raw_rows ]

	return [ normalize_storage_object( row ) for row in raw_rows ]

clear_collection_outputs

clear_collection_outputs() -> None

Clear Collection outputs.

Purpose

Clears Collection tables, document tables, metadata, batch results, and search results without changing configuration controls.

Returns:

Name Type Description
None None

This function updates Streamlit session state.

Source code in app.py
def clear_collection_outputs( ) -> None:
	"""Clear Collection outputs.

	Purpose:
	    Clears Collection tables, document tables, metadata, batch results, and search
	    results without changing configuration controls.

	Returns:
	    None: This function updates Streamlit session state.
	"""
	st.session_state[ 'collections_table' ] = [ ]
	st.session_state[ 'collections_documents_table' ] = [ ]
	st.session_state[ 'collections_metadata' ] = { }
	st.session_state[ 'collections_batch_result' ] = { }
	st.session_state[ 'collections_search_results' ] = [ ]
	st.session_state[ 'collections_selected_id' ] = ''
	st.session_state[ 'collections_id' ] = ''
	st.session_state[ 'collections_next_token' ] = ''

clear_collection_instructions

clear_collection_instructions() -> None

Clear Collection instructions.

Purpose

Clears Collection system instructions and the selected prompt template.

Returns:

Name Type Description
None None

This function updates Streamlit session state.

Source code in app.py
def clear_collection_instructions( ) -> None:
	"""Clear Collection instructions.

	Purpose:
	    Clears Collection system instructions and the selected prompt template.

	Returns:
	    None: This function updates Streamlit session state.
	"""
	st.session_state[ 'collections_system_instructions' ] = ''
	st.session_state[ 'collections_prompt_id' ] = None

load_collection_instruction_template

load_collection_instruction_template() -> None

Load Collection instruction template.

Purpose

Loads the selected prompt template into the Collection system-instruction field.

Returns:

Name Type Description
None None

This function updates Streamlit session state.

Source code in app.py
def load_collection_instruction_template( ) -> None:
	"""Load Collection instruction template.

	Purpose:
	    Loads the selected prompt template into the Collection system-instruction field.

	Returns:
	    None: This function updates Streamlit session state.
	"""
	load_prompt_template( prompt_id_key='collections_prompt_id',
		instructions_key='collections_system_instructions', )

convert_collection_instructions

convert_collection_instructions() -> None

Convert Collection instructions.

Purpose

Converts Collection system instructions between Markdown headings and XML-style heading elements.

Returns:

Name Type Description
None None

This function updates Streamlit session state.

Source code in app.py
def convert_collection_instructions( ) -> None:
	"""Convert Collection instructions.

	Purpose:
	    Converts Collection system instructions between Markdown headings and XML-style
	    heading elements.

	Returns:
	    None: This function updates Streamlit session state.
	"""
	instructions = str( st.session_state.get( 'collections_system_instructions', '' ) or '' )
	if instructions.strip( ):
		st.session_state[ 'collections_system_instructions' ] = convert_markdown(
			instructions )

reset_collection_selection

reset_collection_selection() -> None

Reset Collection-selection controls.

Purpose

Restores the Collection-selection controls to their default values.

Returns:

Name Type Description
None None

This function updates Streamlit session state.

Source code in app.py
def reset_collection_selection( ) -> None:
	"""Reset Collection-selection controls.

	Purpose:
	    Restores the Collection-selection controls to their default values.

	Returns:
	    None: This function updates Streamlit session state.
	"""
	st.session_state[ 'collections_selected_label' ] = ''
	st.session_state[ 'collections_selected_id' ] = ''
	st.session_state[ 'collections_manual_id' ] = ''

reset_collection_documents

reset_collection_documents() -> None

Reset Collection-document controls.

Purpose

Restores the Collection-document controls to their default values.

Returns:

Name Type Description
None None

This function updates Streamlit session state.

Source code in app.py
def reset_collection_documents( ) -> None:
	"""Reset Collection-document controls.

	Purpose:
	    Restores the Collection-document controls to their default values.

	Returns:
	    None: This function updates Streamlit session state.
	"""
	st.session_state.pop( 'collections_uploaded_file', None )
	st.session_state[ 'collections_document_id' ] = ''
	st.session_state[ 'collections_attributes' ] = ''
	st.session_state[ 'collections_document_ids_text' ] = ''

reset_collection_lifecycle

reset_collection_lifecycle() -> None

Reset Collection-lifecycle controls.

Purpose

Restores the Collection-lifecycle controls to their default values.

Returns:

Name Type Description
None None

This function updates Streamlit session state.

Source code in app.py
def reset_collection_lifecycle( ) -> None:
	"""Reset Collection-lifecycle controls.

	Purpose:
	    Restores the Collection-lifecycle controls to their default values.

	Returns:
	    None: This function updates Streamlit session state.
	"""
	st.session_state[ 'collections_name' ] = ''
	st.session_state[ 'collections_description' ] = ''
	st.session_state[ 'collections_id' ] = ''
	st.session_state[ 'collections_team_id' ] = ''
	st.session_state[ 'collections_confirm_delete' ] = False
reset_collection_search() -> None

Reset Collection-search controls.

Purpose

Restores the Collection-search controls to their default values.

Returns:

Name Type Description
None None

This function updates Streamlit session state.

Source code in app.py
def reset_collection_search( ) -> None:
	"""Reset Collection-search controls.

	Purpose:
	    Restores the Collection-search controls to their default values.

	Returns:
	    None: This function updates Streamlit session state.
	"""
	st.session_state[ 'collections_model' ] = ''
	st.session_state[ 'collections_max_results' ] = 10
	st.session_state[ 'collections_filter' ] = ''
	st.session_state[ 'collections_query' ] = ''

reset_collection_system_instructions

reset_collection_system_instructions() -> None

Reset Collection system-instruction controls.

Purpose

Restores the Collection system-instruction controls to their default values.

Returns:

Name Type Description
None None

This function updates Streamlit session state.

Source code in app.py
def reset_collection_system_instructions( ) -> None:
	"""Reset Collection system-instruction controls.

	Purpose:
	    Restores the Collection system-instruction controls to their default values.

	Returns:
	    None: This function updates Streamlit session state.
	"""
	st.session_state[ 'collections_prompt_category' ] = None
	st.session_state[ 'collections_prompt_id' ] = None
	st.session_state[ 'collections_system_instructions' ] = ''

clear_collection_messages

clear_collection_messages() -> None

Clear Collection conversation messages.

Purpose

Removes the user and assistant messages retained by Collections mode.

Returns:

Name Type Description
None None

This function updates Streamlit session state.

Source code in app.py
def clear_collection_messages( ) -> None:
	"""Clear Collection conversation messages.

	Purpose:
	    Removes the user and assistant messages retained by Collections mode.

	Returns:
	    None: This function updates Streamlit session state.
	"""
	st.session_state[ 'collections_messages' ] = [ ]

get_filestore_options

get_filestore_options(
    instance: Any,
    attr_name: str,
    fallback: Optional[List[Any]] = None,
) -> List[Any]

Get File Search Store options.

Purpose

Returns option values exposed by the Gemini FileSearch wrapper.

Parameters:

Name Type Description Default
instance Any

Active Gemini FileSearch wrapper.

required
attr_name str

Wrapper property or method containing option values.

required
fallback Optional[List[Any]]

Values used when the wrapper exposes no options.

None

Returns:

Type Description
List[Any]

List[Any]: Provider-supported option values.

Source code in app.py
def get_filestore_options( instance: Any, attr_name: str,
	fallback: Optional[ List[ Any ] ] = None, ) -> List[ Any ]:
	"""Get File Search Store options.

	Purpose:
	    Returns option values exposed by the Gemini FileSearch wrapper.

	Args:
	    instance (Any): Active Gemini FileSearch wrapper.
	    attr_name (str): Wrapper property or method containing option values.
	    fallback (Optional[List[Any]]): Values used when the wrapper exposes no options.

	Returns:
	    List[Any]: Provider-supported option values.
	"""
	values = getattr( instance, attr_name, None )

	if callable( values ):
		try:
			values = values( )
		except Exception:
			values = None

	if isinstance( values, tuple ):
		values = list( values )

	if isinstance( values, list ):
		return values

	return fallback or [ ]

sanitize_filestore_selection

sanitize_filestore_selection(
    key: str, options: List[Any], default: Any = ""
) -> None

Sanitize File Search Store selection.

Purpose

Clears a stored selection when it is unsupported by the active wrapper.

Parameters:

Name Type Description Default
key str

Session-state key containing the selection.

required
options List[Any]

Provider-supported option values.

required
default Any

Replacement value for an invalid selection.

''

Returns:

Name Type Description
None None

This function updates Streamlit session state.

Source code in app.py
def sanitize_filestore_selection( key: str, options: List[ Any ], default: Any = '', ) -> None:
	"""Sanitize File Search Store selection.

	Purpose:
	    Clears a stored selection when it is unsupported by the active wrapper.

	Args:
	    key (str): Session-state key containing the selection.
	    options (List[Any]): Provider-supported option values.
	    default (Any): Replacement value for an invalid selection.

	Returns:
	    None: This function updates Streamlit session state.
	"""
	current_value = st.session_state.get( key, default )

	if current_value in [ None, '' ]:
		return

	if current_value not in options:
		st.session_state[ key ] = default

parse_filestore_metadata

parse_filestore_metadata(
    value: Any,
) -> Optional[List[Dict[str, Any]]]

Parse File Search Store metadata.

Purpose

Converts optional JSON metadata input into the list of metadata objects accepted by the Gemini File Search Store upload contract.

Parameters:

Name Type Description Default
value Any

Metadata JSON text or existing metadata sequence.

required

Returns:

Type Description
Optional[List[Dict[str, Any]]]

Optional[List[Dict[str, Any]]]: Provider-ready metadata or None.

Raises:

Type Description
ValueError

Raised when nonempty metadata is not a JSON object or array.

Source code in app.py
def parse_filestore_metadata( value: Any, ) -> Optional[ List[ Dict[ str, Any ] ] ]:
	"""Parse File Search Store metadata.

	Purpose:
	    Converts optional JSON metadata input into the list of metadata objects accepted by
	    the Gemini File Search Store upload contract.

	Args:
	    value (Any): Metadata JSON text or existing metadata sequence.

	Returns:
	    Optional[List[Dict[str, Any]]]: Provider-ready metadata or None.

	Raises:
	    ValueError: Raised when nonempty metadata is not a JSON object or array.
	"""
	if value is None:
		return None

	if isinstance( value, list ):
		return value if value else None

	if isinstance( value, dict ):
		return [ value ]

	raw_value = str( value ).strip( )

	if not raw_value:
		return None

	parsed_value = json.loads( raw_value )

	if isinstance( parsed_value, dict ):
		return [ parsed_value ]

	if isinstance( parsed_value, list ):
		for item in parsed_value:
			if not isinstance( item, dict ):
				raise ValueError( 'Each custom metadata entry must be a JSON object.' )

		return parsed_value

	raise ValueError( 'Custom metadata must be a JSON object or array of JSON objects.' )

normalize_filestore_object

normalize_filestore_object(value: Any) -> Dict[str, Any]

Normalize File Search Store object.

Purpose

Converts Gemini File Search Store, upload, operation, and deletion responses into a stable dictionary for display.

Parameters:

Name Type Description Default
value Any

Provider response.

required

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Normalized provider response.

Source code in app.py
def normalize_filestore_object( value: Any, ) -> Dict[ str, Any ]:
	"""Normalize File Search Store object.

	Purpose:
	    Converts Gemini File Search Store, upload, operation, and deletion responses into a
	    stable dictionary for display.

	Args:
	    value (Any): Provider response.

	Returns:
	    Dict[str, Any]: Normalized provider response.
	"""
	if value is None:
		return { }

	if isinstance( value, bool ):
		return { 'success': value, }

	if isinstance( value, dict ):
		return dict( value )

	if hasattr( value, 'model_dump' ):
		try:
			dumped_value = value.model_dump( )

			if isinstance( dumped_value, dict ):
				return dumped_value

			return { 'result': dumped_value, }
		except Exception:
			pass

	if hasattr( value, 'dict' ):
		try:
			dumped_value = value.dict( )

			if isinstance( dumped_value, dict ):
				return dumped_value

			return { 'result': dumped_value, }
		except Exception:
			pass

	result: Dict[ str, Any ] = { }

	for attr_name in [ 'name', 'display_name', 'id', 'state', 'status', 'create_time',
		'update_time', 'operation', 'metadata', 'done', 'error', 'response', ]:
		if hasattr( value, attr_name ):
			result[ attr_name ] = getattr( value, attr_name, )

	if result:
		return normalize( result )

	return { 'result': str( value ), }

get_filestore_items

get_filestore_items(result: Any) -> List[Any]

Get File Search Store items.

Purpose

Extracts store records from Gemini list responses and iterators.

Parameters:

Name Type Description Default
result Any

Gemini File Search Store list result.

required

Returns:

Type Description
List[Any]

List[Any]: Store resource objects.

Source code in app.py
def get_filestore_items( result: Any, ) -> List[ Any ]:
	"""Get File Search Store items.

	Purpose:
	    Extracts store records from Gemini list responses and iterators.

	Args:
	    result (Any): Gemini File Search Store list result.

	Returns:
	    List[Any]: Store resource objects.
	"""
	if result is None:
		return [ ]

	if isinstance( result, list ):
		return result

	if isinstance( result, tuple ):
		return list( result )

	if isinstance( result, dict ):
		for key in [ 'file_search_stores', 'stores', 'data', 'items', ]:
			items = result.get( key )

			if isinstance( items, list ):
				return items

	for attr_name in [ 'file_search_stores', 'stores', 'data', 'items', ]:
		items = getattr( result, attr_name, None )

		if items is not None:
			try:
				return list( items )
			except Exception:
				pass

	try:
		return list( result )
	except Exception:
		return [ result ]

normalize_filestore_rows

normalize_filestore_rows(
    result: Any,
) -> List[Dict[str, Any]]

Normalize File Search Store rows.

Purpose

Converts Gemini File Search Store resources into rows used by the management table and selector.

Parameters:

Name Type Description Default
result Any

Gemini list response.

required

Returns:

Type Description
List[Dict[str, Any]]

List[Dict[str, Any]]: Normalized store rows.

Source code in app.py
def normalize_filestore_rows( result: Any, ) -> List[ Dict[ str, Any ] ]:
	"""Normalize File Search Store rows.

	Purpose:
	    Converts Gemini File Search Store resources into rows used by the management table
	    and selector.

	Args:
	    result (Any): Gemini list response.

	Returns:
	    List[Dict[str, Any]]: Normalized store rows.
	"""
	rows: List[ Dict[ str, Any ] ] = [ ]

	for item in get_filestore_items( result ):
		metadata = normalize_filestore_object( item )
		store_id = str( metadata.get( 'name' ) or metadata.get( 'id' ) or '' )
		display_name = str(
			metadata.get( 'display_name' ) or metadata.get( 'displayName' ) or store_id or '' )
		state = str( metadata.get( 'state' ) or metadata.get( 'status' ) or '' )
		create_time = str( metadata.get( 'create_time' ) or metadata.get( 'createTime' ) or
		                   '' )
		update_time = str( metadata.get( 'update_time' ) or metadata.get( 'updateTime' ) or
		                   '' )

		if store_id:
			rows.append(
				{ 'id': store_id, 'name': display_name, 'state': state, 'created': create_time,
					'updated': update_time, } )

	return rows

get_selected_filestore_id

get_selected_filestore_id() -> str

Get selected File Search Store identifier.

Purpose

Returns the manually entered store resource name or the current table selection.

Returns:

Name Type Description
str str

Active Gemini File Search Store resource name.

Source code in app.py
def get_selected_filestore_id( ) -> str:
	"""Get selected File Search Store identifier.

	Purpose:
	    Returns the manually entered store resource name or the current table selection.

	Returns:
	    str: Active Gemini File Search Store resource name.
	"""
	manual_id = str( st.session_state.get( 'filestore_manual_id', '', ) or '' ).strip( )

	if manual_id:
		return manual_id

	return str( st.session_state.get( 'filestore_selected_id', '', ) or '' ).strip( )

clear_filestore_outputs

clear_filestore_outputs() -> None

Clear File Search Store outputs.

Purpose

Removes File Search Store operation results without changing store selections, request settings, uploaded-file controls, queries, or system instructions.

Returns:

Name Type Description
None None

This function updates Streamlit session state.

Source code in app.py
def clear_filestore_outputs( ) -> None:
	"""Clear File Search Store outputs.

	Purpose:
	    Removes File Search Store operation results without changing store selections,
	    request settings, uploaded-file controls, queries, or system instructions.

	Returns:
	    None: This function updates Streamlit session state.
	"""
	st.session_state[ 'filestore_results' ] = None
	st.session_state[ 'filestore_metadata' ] = { }
	st.session_state[ 'filestore_upload_result' ] = { }

clear_filestore_instructions

clear_filestore_instructions() -> None

Clear File Search Stores instructions.

Purpose

Clears File Search Stores system instructions and the selected prompt template.

Returns:

Name Type Description
None None

This function updates Streamlit session state.

Source code in app.py
def clear_filestore_instructions( ) -> None:
	"""Clear File Search Stores instructions.

	Purpose:
	    Clears File Search Stores system instructions and the selected prompt template.

	Returns:
	    None: This function updates Streamlit session state.
	"""
	st.session_state[ 'filestore_system_instructions' ] = ''
	st.session_state[ 'filestore_prompt_id' ] = None

convert_filestore_system_instructions

convert_filestore_system_instructions() -> None

Convert File Search Stores system instructions.

Purpose

Converts File Search Stores instructions between XML blocks and Markdown headings.

Returns:

Name Type Description
None None

This function updates Streamlit session state.

Source code in app.py
def convert_filestore_system_instructions( ) -> None:
	"""Convert File Search Stores system instructions.

	Purpose:
	    Converts File Search Stores instructions between XML blocks and Markdown headings.

	Returns:
	    None: This function updates Streamlit session state.
	"""
	text_value = str(
		st.session_state.get( 'filestore_system_instructions', '', ) or '' ).strip( )

	if not text_value:
		return

	if cfg.XML_BLOCK_PATTERN.search( text_value ):
		st.session_state[ 'filestore_system_instructions' ] = convert_xml( text_value )
	else:
		st.session_state[ 'filestore_system_instructions' ] = convert_markdown( text_value )

load_filestore_instruction_template

load_filestore_instruction_template() -> None

Load File Search Stores instruction template.

Purpose

Loads the selected File Search Stores prompt template into the system-instruction field.

Returns:

Name Type Description
None None

This function updates Streamlit session state.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in app.py
def load_filestore_instruction_template( ) -> None:
	"""Load File Search Stores instruction template.

	Purpose:
	    Loads the selected File Search Stores prompt template into the system-instruction
	    field.

	Returns:
	    None: This function updates Streamlit session state.

	Raises:
	    Error: Re-raised after the exception is logged.
	"""
	try:
		load_prompt_template( prompt_id_key='filestore_prompt_id',
			instructions_key='filestore_system_instructions', )
	except Exception as e:
		ex = Error( e )
		ex.module = 'app'
		ex.cause = 'File Search Stores'
		ex.method = ('load_filestore_instruction_template( self ) -> None')
		Logger( ).write( ex )
		raise ex

reset_filestore_management_settings

reset_filestore_management_settings() -> None

Reset File Search Store management settings.

Purpose

Returns store-management controls to their initial values without modifying provider resources or request output.

Returns:

Name Type Description
None None

This function updates Streamlit session state.

Source code in app.py
def reset_filestore_management_settings( ) -> None:
	"""Reset File Search Store management settings.

	Purpose:
	    Returns store-management controls to their initial values without modifying provider
	    resources or request output.

	Returns:
	    None: This function updates Streamlit session state.
	"""
	for key in [ 'filestore_name', 'filestore_embedding_model', 'filestore_selected_id',
		'filestore_selected_label', 'filestore_manual_id', 'filestore_force_delete',
		'filestore_confirm_delete', ]:
		if key in st.session_state:
			del st.session_state[ key ]

reset_filestore_request_settings

reset_filestore_request_settings() -> None

Reset File Search Store request settings.

Purpose

Returns supported Gemini File Search query settings to their initial values without clearing stores, uploads, queries, results, or instructions.

Returns:

Name Type Description
None None

This function updates Streamlit session state.

Source code in app.py
def reset_filestore_request_settings( ) -> None:
	"""Reset File Search Store request settings.

	Purpose:
	    Returns supported Gemini File Search query settings to their initial values without
	    clearing stores, uploads, queries, results, or instructions.

	Returns:
	    None: This function updates Streamlit session state.
	"""
	for key in [ 'filestore_model', 'filestore_temperature', 'filestore_top_percent',
		'filestore_max_tokens', 'filestore_frequency_penalty', 'filestore_presence_penalty',
		'filestore_response_format', 'filestore_metadata_filter', 'filestore_tool_choice',
		'filestore_reasoning', 'filestore_store', 'filestore_stream',
		'filestore_background', ]:
		if key in st.session_state:
			del st.session_state[ key ]

refresh_filestore_table

refresh_filestore_table() -> List[Dict[str, Any]]

Refresh File Search Store table.

Purpose

Lists Gemini File Search Stores and stores normalized table rows and display-name mappings.

Returns:

Type Description
List[Dict[str, Any]]

List[Dict[str, Any]]: Normalized File Search Store rows.

Source code in app.py
def refresh_filestore_table( ) -> List[ Dict[ str, Any ] ]:
	"""Refresh File Search Store table.

	Purpose:
	    Lists Gemini File Search Stores and stores normalized table rows and display-name
	    mappings.

	Returns:
	    List[Dict[str, Any]]: Normalized File Search Store rows.
	"""
	result = searcher.list( )
	rows = normalize_filestore_rows( result )
	st.session_state[ 'filestore_table' ] = rows

	collections = getattr( searcher, 'collections', { }, )

	if isinstance( collections, dict ):
		st.session_state[ 'text_file_search_store_names' ] = list( collections.values( ) )

	return rows

create_filestore

create_filestore() -> Dict[str, Any]

Create File Search Store.

Purpose

Creates a Gemini File Search Store using the exact wrapper contract.

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Normalized created-store metadata.

Source code in app.py
def create_filestore( ) -> Dict[ str, Any ]:
	"""Create File Search Store.

	Purpose:
	    Creates a Gemini File Search Store using the exact wrapper contract.

	Returns:
	    Dict[str, Any]: Normalized created-store metadata.
	"""
	name = str( st.session_state.get( 'filestore_name', '', ) or '' ).strip( )
	embedding_model = str(
		st.session_state.get( 'filestore_embedding_model', '', ) or '' ).strip( )

	throw_if( 'name', name )
	throw_if( 'embedding_model', embedding_model )

	result = searcher.create( name=name, embedding_model=embedding_model, )
	metadata = normalize_filestore_object( result )
	store_id = str(
		metadata.get( 'name' ) or metadata.get( 'id' ) or getattr( searcher, 'store_id',
			'' ) or '' )

	st.session_state[ 'filestore_metadata' ] = metadata
	st.session_state[ 'filestore_manual_id' ] = store_id
	st.session_state[ 'filestore_selected_id' ] = store_id
	st.session_state[ 'filestore_selected_label' ] = store_id

	return metadata

retrieve_filestore

retrieve_filestore(store_id: str) -> Dict[str, Any]

Retrieve File Search Store.

Purpose

Retrieves Gemini File Search Store metadata using the exact wrapper contract.

Parameters:

Name Type Description Default
store_id str

Required Gemini File Search Store resource name.

required

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Normalized store metadata.

Source code in app.py
def retrieve_filestore( store_id: str, ) -> Dict[ str, Any ]:
	"""Retrieve File Search Store.

	Purpose:
	    Retrieves Gemini File Search Store metadata using the exact wrapper contract.

	Args:
	    store_id (str): Required Gemini File Search Store resource name.

	Returns:
	    Dict[str, Any]: Normalized store metadata.
	"""
	throw_if( 'store_id', store_id )
	result = searcher.retrieve( store_id=store_id, )
	metadata = normalize_filestore_object( result )
	st.session_state[ 'filestore_metadata' ] = metadata
	return metadata

delete_filestore

delete_filestore(store_id: str) -> Dict[str, Any]

Delete File Search Store.

Purpose

Deletes a Gemini File Search Store using the exact wrapper contract and explicit force-selection state.

Parameters:

Name Type Description Default
store_id str

Required Gemini File Search Store resource name.

required

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Normalized deletion result.

Source code in app.py
def delete_filestore( store_id: str, ) -> Dict[ str, Any ]:
	"""Delete File Search Store.

	Purpose:
	    Deletes a Gemini File Search Store using the exact wrapper contract and explicit
	    force-selection state.

	Args:
	    store_id (str): Required Gemini File Search Store resource name.

	Returns:
	    Dict[str, Any]: Normalized deletion result.
	"""
	throw_if( 'store_id', store_id )
	result = searcher.delete( store_id=store_id,
		force=bool( st.session_state.get( 'filestore_force_delete', True, ) ), )
	metadata = normalize_filestore_object( result )
	st.session_state[ 'filestore_metadata' ] = metadata
	st.session_state[ 'filestore_table' ] = [ row for row in
		st.session_state.get( 'filestore_table', [ ], ) if
		isinstance( row, dict ) and row.get( 'id' ) != store_id ]
	st.session_state[ 'filestore_selected_id' ] = ''
	st.session_state[ 'filestore_selected_label' ] = ''
	st.session_state[ 'filestore_manual_id' ] = ''
	return metadata

upload_filestore_file

upload_filestore_file(
    uploaded_file: Any, store_id: str
) -> Dict[str, Any]

Upload File Search Store file.

Purpose

Stages and uploads a file through the exact Gemini File Search Store upload contract.

Parameters:

Name Type Description Default
uploaded_file Any

Streamlit uploaded-file object.

required
store_id str

Required Gemini File Search Store resource name.

required

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Normalized upload or import-operation result.

Source code in app.py
def upload_filestore_file( uploaded_file: Any, store_id: str, ) -> Dict[ str, Any ]:
	"""Upload File Search Store file.

	Purpose:
	    Stages and uploads a file through the exact Gemini File Search Store upload contract.

	Args:
	    uploaded_file (Any): Streamlit uploaded-file object.
	    store_id (str): Required Gemini File Search Store resource name.

	Returns:
	    Dict[str, Any]: Normalized upload or import-operation result.
	"""
	throw_if( 'uploaded_file', uploaded_file )
	throw_if( 'store_id', store_id )

	file_path = save_uploaded_storage_file( uploaded_file )
	throw_if( 'file_path', file_path )

	result = searcher.upload_file( path=file_path, store_id=store_id, display_name=str(
		getattr( uploaded_file, 'name', Path( file_path ).name, ) or Path( file_path ).name ),
		mime_type=str( getattr( uploaded_file, 'type', '', ) or '' ),
		custom_metadata=parse_filestore_metadata(
			st.session_state.get( 'filestore_custom_metadata', '', ) ), )
	metadata = normalize_filestore_object( result )
	st.session_state[ 'filestore_upload_result' ] = metadata
	return metadata

search_filestore

search_filestore(store_id: str, query: str) -> str

Search File Search Store.

Purpose

Executes a grounded Gemini File Search Store query using only parameters implemented by the uploaded wrapper.

Parameters:

Name Type Description Default
store_id str

Required Gemini File Search Store resource name.

required
query str

Required grounded query.

required

Returns:

Name Type Description
str str

Gemini grounded response text.

Source code in app.py
def search_filestore( store_id: str, query: str, ) -> str:
	"""Search File Search Store.

	Purpose:
	    Executes a grounded Gemini File Search Store query using only parameters implemented
	    by the uploaded wrapper.

	Args:
	    store_id (str): Required Gemini File Search Store resource name.
	    query (str): Required grounded query.

	Returns:
	    str: Gemini grounded response text.
	"""
	throw_if( 'store_id', store_id )
	throw_if( 'query', query )

	model = str( st.session_state.get( 'filestore_model', '', ) or '' ).strip( )
	throw_if( 'model', model )

	result = searcher.search( store_id=store_id, query=query, model=model,
		temperature=float( st.session_state.get( 'filestore_temperature', 0.0, ) or 0.0 ),
		top_p=float( st.session_state.get( 'filestore_top_percent', 0.0, ) or 0.0 ),
		frequency=float( st.session_state.get( 'filestore_frequency_penalty', 0.0, ) or 0.0 ),
		presence=float( st.session_state.get( 'filestore_presence_penalty', 0.0, ) or 0.0 ),
		max_tokens=int( st.session_state.get( 'filestore_max_tokens', 0, ) or 0 ),
		response_format=str( st.session_state.get( 'filestore_response_format', '', ) or '' ),
		instruct=str( st.session_state.get( 'filestore_system_instructions', '', ) or '' ),
		metadata_filter=str( st.session_state.get( 'filestore_metadata_filter', '', ) or ''
		), )

	if isinstance( result, str ):
		return result.strip( )

	return str( getattr( searcher, 'output_text', '', ) or getattr( result, 'text',
		'', ) or result or '' ).strip( )

get_bucket_options

get_bucket_options(
    instance: Any,
    attr_name: str,
    fallback: Optional[List[Any]] = None,
) -> List[Any]

Get bucket options.

Purpose

Returns provider-supported values exposed by the Gemini CloudBuckets wrapper.

Parameters:

Name Type Description Default
instance Any

Active Gemini CloudBuckets wrapper.

required
attr_name str

Wrapper option property or method name.

required
fallback Optional[List[Any]]

Values used when no wrapper options are exposed.

None

Returns:

Type Description
List[Any]

List[Any]: Provider-supported option values.

Source code in app.py
def get_bucket_options( instance: Any, attr_name: str,
	fallback: Optional[ List[ Any ] ] = None, ) -> List[ Any ]:
	"""Get bucket options.

	Purpose:
	    Returns provider-supported values exposed by the Gemini CloudBuckets wrapper.

	Args:
	    instance (Any): Active Gemini CloudBuckets wrapper.
	    attr_name (str): Wrapper option property or method name.
	    fallback (Optional[List[Any]]): Values used when no wrapper options are exposed.

	Returns:
	    List[Any]: Provider-supported option values.
	"""
	values = getattr( instance, attr_name, None, )

	if callable( values ):
		try:
			values = values( )
		except Exception:
			values = None

	if isinstance( values, tuple ):
		values = list( values )

	if isinstance( values, list ):
		return values

	return fallback or [ ]

sanitize_bucket_selection

sanitize_bucket_selection(
    key: str, options: List[Any], default: Any = ""
) -> None

Sanitize bucket selection.

Purpose

Clears a stored single-selection value that is unsupported by the active wrapper.

Parameters:

Name Type Description Default
key str

Session-state key containing the selection.

required
options List[Any]

Provider-supported option values.

required
default Any

Replacement value for an unsupported selection.

''

Returns:

Name Type Description
None None

This function updates Streamlit session state.

Source code in app.py
def sanitize_bucket_selection( key: str, options: List[ Any ], default: Any = '', ) -> None:
	"""Sanitize bucket selection.

	Purpose:
	    Clears a stored single-selection value that is unsupported by the active wrapper.

	Args:
	    key (str): Session-state key containing the selection.
	    options (List[Any]): Provider-supported option values.
	    default (Any): Replacement value for an unsupported selection.

	Returns:
	    None: This function updates Streamlit session state.
	"""
	current_value = st.session_state.get( key, default, )

	if current_value in [ None, '' ]:
		return

	if current_value not in options:
		st.session_state[ key ] = default

normalize_bucket_object

normalize_bucket_object(value: Any) -> Dict[str, Any]

Normalize bucket object.

Purpose

Converts Google Cloud Storage bucket and object responses into dictionaries suitable for Streamlit tables and metadata output.

Parameters:

Name Type Description Default
value Any

Google Cloud Storage bucket, blob, boolean, or dictionary response.

required

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Normalized bucket or object metadata.

Source code in app.py
def normalize_bucket_object( value: Any, ) -> Dict[ str, Any ]:
	"""Normalize bucket object.

	Purpose:
	    Converts Google Cloud Storage bucket and object responses into dictionaries suitable
	    for Streamlit tables and metadata output.

	Args:
	    value (Any): Google Cloud Storage bucket, blob, boolean, or dictionary response.

	Returns:
	    Dict[str, Any]: Normalized bucket or object metadata.
	"""
	if value is None:
		return { }

	if isinstance( value, bool ):
		return { 'success': value, }

	if isinstance( value, dict ):
		return normalize( value )

	if hasattr( value, 'model_dump' ):
		try:
			dumped_value = value.model_dump( )

			if isinstance( dumped_value, dict ):
				return normalize( dumped_value )
		except Exception:
			pass

	value_bucket = getattr( value, 'bucket', None, )
	bucket_name = str(
		getattr( value_bucket, 'name', '', ) or getattr( value, 'bucket_name', '', ) or '' )
	object_name = str( getattr( value, 'name', '', ) or '' )

	# A Blob exposes a bucket reference. A Bucket normally does not.
	if value_bucket is not None:
		return { 'id': str( getattr( value, 'id', '', ) or '' ), 'name': object_name,
			'bucket': bucket_name,
			'content_type': str( getattr( value, 'content_type', '', ) or '' ),
			'size': getattr( value, 'size', 0, ),
			'generation': getattr( value, 'generation', None, ),
			'metageneration': getattr( value, 'metageneration', None, ),
			'md5_hash': str( getattr( value, 'md5_hash', '', ) or '' ),
			'crc32c': str( getattr( value, 'crc32c', '', ) or '' ),
			'time_created': str( getattr( value, 'time_created', '', ) or '' ),
			'updated': str( getattr( value, 'updated', '', ) or '' ),
			'storage_class': str( getattr( value, 'storage_class', '', ) or '' ),
			'metadata': normalize( getattr( value, 'metadata', None, ) ), 'uri': (
				f'gs://{bucket_name}/{object_name}' if bucket_name and object_name else ''), }

	return { 'id': str( getattr( value, 'id', '', ) or '' ),
		'name': str( getattr( value, 'name', '', ) or '' ),
		'project_number': str( getattr( value, 'project_number', '', ) or '' ),
		'location': str( getattr( value, 'location', '', ) or '' ),
		'storage_class': str( getattr( value, 'storage_class', '', ) or '' ),
		'time_created': str( getattr( value, 'time_created', '', ) or '' ),
		'updated': str( getattr( value, 'updated', '', ) or '' ),
		'versioning_enabled': getattr( value, 'versioning_enabled', False, ),
		'retention_period': getattr( value, 'retention_period', None, ),
		'labels': normalize( getattr( value, 'labels', None, ) ),
		'self_link': str( getattr( value, 'self_link', '', ) or '' ), }

normalize_bucket_rows

normalize_bucket_rows(result: Any) -> List[Dict[str, Any]]

Normalize bucket rows.

Purpose

Converts Google Cloud Storage object-list responses into stable table rows.

Parameters:

Name Type Description Default
result Any

Google Cloud Storage object collection.

required

Returns:

Type Description
List[Dict[str, Any]]

List[Dict[str, Any]]: Normalized object metadata rows.

Source code in app.py
def normalize_bucket_rows( result: Any, ) -> List[ Dict[ str, Any ] ]:
	"""Normalize bucket rows.

	Purpose:
	    Converts Google Cloud Storage object-list responses into stable table rows.

	Args:
	    result (Any): Google Cloud Storage object collection.

	Returns:
	    List[Dict[str, Any]]: Normalized object metadata rows.
	"""
	if result is None:
		return [ ]

	if isinstance( result, list ):
		items = result
	elif isinstance( result, tuple ):
		items = list( result )
	else:
		try:
			items = list( result )
		except Exception:
			items = [ result ]

	rows: List[ Dict[ str, Any ] ] = [ ]

	for item in items:
		metadata = normalize_bucket_object( item )

		if not metadata:
			continue

		rows.append( { 'id': str( metadata.get( 'id', '', ) or '' ),
			'name': str( metadata.get( 'name', '', ) or '' ),
			'content_type': str( metadata.get( 'content_type', '', ) or '' ),
			'size': metadata.get( 'size', 0, ),
			'updated': str( metadata.get( 'updated', '', ) or '' ),
			'uri': str( metadata.get( 'uri', '', ) or '' ), } )

	return rows

get_selected_bucket_name

get_selected_bucket_name() -> str

Get selected bucket name.

Purpose

Returns the manually entered bucket name or the currently selected configured bucket.

Returns:

Name Type Description
str str

Active Google Cloud Storage bucket name.

Source code in app.py
def get_selected_bucket_name( ) -> str:
	"""Get selected bucket name.

	Purpose:
	    Returns the manually entered bucket name or the currently selected configured bucket.

	Returns:
	    str: Active Google Cloud Storage bucket name.
	"""
	manual_name = str( st.session_state.get( 'bucket_manual_id', '', ) or '' ).strip( )

	if manual_name:
		return manual_name

	return str( st.session_state.get( 'bucket_selected_id', '', ) or '' ).strip( )

save_bucket_upload

save_bucket_upload(uploaded_file: Any) -> str

Save bucket upload.

Purpose

Writes a Streamlit uploaded file to a temporary local path for Google Cloud Storage upload.

Parameters:

Name Type Description Default
uploaded_file Any

Streamlit uploaded-file object.

required

Returns:

Name Type Description
str str

Temporary local file path.

Source code in app.py
def save_bucket_upload( uploaded_file: Any, ) -> str:
	"""Save bucket upload.

	Purpose:
	    Writes a Streamlit uploaded file to a temporary local path for Google Cloud Storage
	    upload.

	Args:
	    uploaded_file (Any): Streamlit uploaded-file object.

	Returns:
	    str: Temporary local file path.
	"""
	throw_if( 'uploaded_file', uploaded_file, )

	path = save_uploaded_storage_file( uploaded_file )
	throw_if( 'path', path, )
	return str( path )

clear_bucket_outputs

clear_bucket_outputs() -> None

Clear bucket outputs.

Purpose

Clears Google Cloud Bucket operation results without changing bucket selections, request settings, uploaded files, queries, or system instructions.

Returns:

Name Type Description
None None

This function updates Streamlit session state.

Source code in app.py
def clear_bucket_outputs( ) -> None:
	"""Clear bucket outputs.

	Purpose:
	    Clears Google Cloud Bucket operation results without changing bucket selections,
	    request settings, uploaded files, queries, or system instructions.

	Returns:
	    None: This function updates Streamlit session state.
	"""
	st.session_state[ 'bucket_results' ] = None
	st.session_state[ 'bucket_metadata' ] = { }
	st.session_state[ 'bucket_upload_result' ] = { }
	st.session_state[ 'bucket_table' ] = [ ]

clear_bucket_instructions

clear_bucket_instructions() -> None

Clear Google Cloud Buckets instructions.

Purpose

Clears the Google Cloud Buckets system-instruction text and selected prompt template without changing the selected category, bucket configuration, results, or uploaded files.

Returns:

Name Type Description
None None

This function updates Streamlit session state.

Source code in app.py
def clear_bucket_instructions( ) -> None:
	"""Clear Google Cloud Buckets instructions.

	Purpose:
	    Clears the Google Cloud Buckets system-instruction text and selected prompt template
	    without changing the selected category, bucket configuration, results, or uploaded
	    files.

	Returns:
	    None: This function updates Streamlit session state.
	"""
	st.session_state[ 'bucket_system_instructions' ] = ''
	st.session_state[ 'bucket_prompt_id' ] = None

convert_bucket_system_instructions

convert_bucket_system_instructions() -> None

Convert Google Cloud Buckets system instructions.

Purpose

Converts the active Google Cloud Buckets system instructions between supported XML-style instruction blocks and Markdown headings.

Returns:

Name Type Description
None None

This function updates Streamlit session state.

Source code in app.py
def convert_bucket_system_instructions( ) -> None:
	"""Convert Google Cloud Buckets system instructions.

	Purpose:
	    Converts the active Google Cloud Buckets system instructions between supported
	    XML-style instruction blocks and Markdown headings.

	Returns:
	    None: This function updates Streamlit session state.
	"""
	text_value = str( st.session_state.get( 'bucket_system_instructions', '', ) or ''
	).strip( )

	if not text_value:
		return

	if cfg.XML_BLOCK_PATTERN.search( text_value ):
		st.session_state[ 'bucket_system_instructions' ] = convert_xml( text_value )
	else:
		st.session_state[ 'bucket_system_instructions' ] = convert_markdown( text_value )

load_bucket_instruction_template

load_bucket_instruction_template() -> None

Load Google Cloud Buckets instruction template.

Purpose

Loads the selected Google Cloud Buckets prompt template into the mode-specific system-instruction field.

Returns:

Name Type Description
None None

This function updates Streamlit session state.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Source code in app.py
def load_bucket_instruction_template( ) -> None:
	"""Load Google Cloud Buckets instruction template.

	Purpose:
	    Loads the selected Google Cloud Buckets prompt template into the mode-specific
	    system-instruction field.

	Returns:
	    None: This function updates Streamlit session state.

	Raises:
	    Error: Re-raised after the exception is logged.
	"""
	try:
		load_prompt_template( prompt_id_key='bucket_prompt_id',
			instructions_key='bucket_system_instructions', )
	except Exception as e:
		ex = Error( e )
		ex.module = 'app'
		ex.cause = 'Google Cloud Buckets Mode'
		ex.method = ('load_bucket_instruction_template( ) -> None')
		Logger( ).write( ex )
		raise ex

reset_bucket_management_settings

reset_bucket_management_settings() -> None

Reset bucket management settings.

Purpose

Returns the Google Cloud Bucket management controls to their initial values without clearing provider resources, operation results, request settings, or instructions.

Returns:

Name Type Description
None None

This function updates Streamlit session state.

Source code in app.py
def reset_bucket_management_settings( ) -> None:
	"""Reset bucket management settings.

	Purpose:
	    Returns the Google Cloud Bucket management controls to their initial values without
	    clearing provider resources, operation results, request settings, or instructions.

	Returns:
	    None: This function updates Streamlit session state.
	"""
	for key in [ 'bucket_name', 'bucket_selected_id', 'bucket_selected_label',
		'bucket_manual_id', 'bucket_object_name', 'bucket_prefix', 'bucket_storage_location',
		'bucket_confirm_delete', 'bucket_delete_object_only', ]:
		if key in st.session_state:
			del st.session_state[ key ]

reset_bucket_request_settings

reset_bucket_request_settings() -> None

Reset bucket request settings.

Purpose

Returns the Google Cloud Bucket model, inference, and response controls to their initial values without clearing bucket selections, queries, results, or instructions.

Returns:

Name Type Description
None None

This function updates Streamlit session state.

Source code in app.py
def reset_bucket_request_settings( ) -> None:
	"""Reset bucket request settings.

	Purpose:
	    Returns the Google Cloud Bucket model, inference, and response controls to their
	    initial values without clearing bucket selections, queries, results, or instructions.

	Returns:
	    None: This function updates Streamlit session state.
	"""
	for key in [ 'bucket_model', 'bucket_number', 'bucket_temperature', 'bucket_top_percent',
		'bucket_max_tokens', 'bucket_frequency_penalty', 'bucket_presence_penalty',
		'bucket_response_format', 'bucket_tool_choice', 'bucket_reasoning', 'bucket_store',
		'bucket_stream', 'bucket_background', 'bucket_max_files', 'bucket_location',
		'bucket_project_id', ]:
		if key in st.session_state:
			del st.session_state[ key ]

create_cloud_bucket

create_cloud_bucket() -> Dict[str, Any]

Create cloud bucket.

Purpose

Creates a Google Cloud Storage bucket using the exact Gemini CloudBuckets contract.

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Normalized created-bucket metadata.

Source code in app.py
def create_cloud_bucket( ) -> Dict[ str, Any ]:
	"""Create cloud bucket.

	Purpose:
	    Creates a Google Cloud Storage bucket using the exact Gemini CloudBuckets contract.

	Returns:
	    Dict[str, Any]: Normalized created-bucket metadata.
	"""
	bucket_name = str( st.session_state.get( 'bucket_name', '', ) or '' ).strip( )
	project_id = str( st.session_state.get( 'bucket_project_id', '', ) or '' ).strip( )
	location = str( st.session_state.get( 'bucket_storage_location', 'US', ) or 'US' ).strip( )

	throw_if( 'bucket_name', bucket_name, )
	throw_if( 'project_id', project_id, )
	throw_if( 'location', location, )

	result = buckets.create( name=bucket_name, project_id=project_id, location=location, )
	metadata = normalize_bucket_object( result )
	st.session_state[ 'bucket_metadata' ] = metadata
	st.session_state[ 'bucket_manual_id' ] = bucket_name
	st.session_state[ 'bucket_selected_id' ] = bucket_name
	st.session_state[ 'bucket_selected_label' ] = bucket_name
	return metadata

retrieve_cloud_bucket

retrieve_cloud_bucket(
    bucket_name: str, object_name: str = ""
) -> Dict[str, Any]

Retrieve cloud bucket.

Purpose

Retrieves Google Cloud Storage bucket or object metadata using the exact wrapper contract.

Parameters:

Name Type Description Default
bucket_name str

Required Google Cloud Storage bucket name.

required
object_name str

Optional object name.

''

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Normalized bucket or object metadata.

Source code in app.py
def retrieve_cloud_bucket( bucket_name: str, object_name: str = '', ) -> Dict[ str, Any ]:
	"""Retrieve cloud bucket.

	Purpose:
	    Retrieves Google Cloud Storage bucket or object metadata using the exact wrapper
	    contract.

	Args:
	    bucket_name (str): Required Google Cloud Storage bucket name.
	    object_name (str): Optional object name.

	Returns:
	    Dict[str, Any]: Normalized bucket or object metadata.
	"""
	throw_if( 'bucket_name', bucket_name, )

	result = buckets.retrieve( bucket=bucket_name, object_name=object_name,
		project_id=str( st.session_state.get( 'bucket_project_id', '', ) or '' ), )
	metadata = normalize_bucket_object( result )
	st.session_state[ 'bucket_metadata' ] = metadata
	return metadata

list_cloud_bucket_objects

list_cloud_bucket_objects(
    bucket_name: str,
) -> List[Dict[str, Any]]

List cloud bucket objects.

Purpose

Lists Google Cloud Storage object metadata using the exact wrapper contract.

Parameters:

Name Type Description Default
bucket_name str

Required Google Cloud Storage bucket name.

required

Returns:

Type Description
List[Dict[str, Any]]

List[Dict[str, Any]]: Normalized object rows.

Source code in app.py
def list_cloud_bucket_objects( bucket_name: str, ) -> List[ Dict[ str, Any ] ]:
	"""List cloud bucket objects.

	Purpose:
	    Lists Google Cloud Storage object metadata using the exact wrapper contract.

	Args:
	    bucket_name (str): Required Google Cloud Storage bucket name.

	Returns:
	    List[Dict[str, Any]]: Normalized object rows.
	"""
	throw_if( 'bucket_name', bucket_name, )

	result = buckets.list_objects( bucket=bucket_name,
		prefix=str( st.session_state.get( 'bucket_prefix', '', ) or '' ),
		project_id=str( st.session_state.get( 'bucket_project_id', '', ) or '' ), )
	rows = normalize_bucket_rows( result )
	st.session_state[ 'bucket_table' ] = rows
	return rows

upload_cloud_bucket_object

upload_cloud_bucket_object(
    uploaded_file: Any, bucket_name: str
) -> Dict[str, Any]

Upload cloud bucket object.

Purpose

Uploads a local file to Google Cloud Storage using the exact wrapper contract.

Parameters:

Name Type Description Default
uploaded_file Any

Streamlit uploaded-file object.

required
bucket_name str

Required Google Cloud Storage bucket name.

required

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Normalized uploaded-object metadata.

Source code in app.py
def upload_cloud_bucket_object( uploaded_file: Any, bucket_name: str, ) -> Dict[ str, Any ]:
	"""Upload cloud bucket object.

	Purpose:
	    Uploads a local file to Google Cloud Storage using the exact wrapper contract.

	Args:
	    uploaded_file (Any): Streamlit uploaded-file object.
	    bucket_name (str): Required Google Cloud Storage bucket name.

	Returns:
	    Dict[str, Any]: Normalized uploaded-object metadata.
	"""
	throw_if( 'uploaded_file', uploaded_file, )
	throw_if( 'bucket_name', bucket_name, )

	path = save_bucket_upload( uploaded_file )
	object_name = str(
		st.session_state.get( 'bucket_object_name', '', ) or getattr( uploaded_file, 'name',
			Path( path ).name, ) or Path( path ).name ).strip( )
	content_type = str(
		st.session_state.get( 'bucket_content_type', '', ) or getattr( uploaded_file, 'type',
			'', ) or '' ).strip( )

	result = buckets.upload_file( path=path, bucket=bucket_name, object_name=object_name,
		content_type=content_type,
		project_id=str( st.session_state.get( 'bucket_project_id', '', ) or '' ), )
	metadata = normalize_bucket_object( result )
	st.session_state[ 'bucket_upload_result' ] = metadata
	st.session_state[ 'bucket_object_name' ] = object_name
	return metadata

delete_cloud_bucket_resource

delete_cloud_bucket_resource(
    bucket_name: str, object_name: str = ""
) -> bool

Delete cloud bucket resource.

Purpose

Deletes a Google Cloud Storage bucket or object using the exact wrapper contract.

Parameters:

Name Type Description Default
bucket_name str

Required Google Cloud Storage bucket name.

required
object_name str

Optional object name. An empty value deletes the bucket.

''

Returns:

Name Type Description
bool bool

True when the deletion request completes.

Source code in app.py
def delete_cloud_bucket_resource( bucket_name: str, object_name: str = '', ) -> bool:
	"""Delete cloud bucket resource.

	Purpose:
	    Deletes a Google Cloud Storage bucket or object using the exact wrapper contract.

	Args:
	    bucket_name (str): Required Google Cloud Storage bucket name.
	    object_name (str): Optional object name. An empty value deletes the bucket.

	Returns:
	    bool: True when the deletion request completes.
	"""
	throw_if( 'bucket_name', bucket_name, )

	result = buckets.delete( bucket=bucket_name, object_name=object_name,
		project_id=str( st.session_state.get( 'bucket_project_id', '', ) or '' ), )

	if object_name:
		st.session_state[ 'bucket_table' ] = [ row for row in
			st.session_state.get( 'bucket_table', [ ], ) if
			isinstance( row, dict, ) and row.get( 'name' ) != object_name ]
	else:
		st.session_state[ 'bucket_selected_id' ] = ''
		st.session_state[ 'bucket_selected_label' ] = ''
		st.session_state[ 'bucket_manual_id' ] = ''
		st.session_state[ 'bucket_table' ] = [ ]

	st.session_state[ 'bucket_metadata' ] = { 'success': bool( result ), 'bucket': bucket_name,
		'object_name': object_name, }
	return bool( result )

query_cloud_bucket

query_cloud_bucket(bucket_name: str, query: str) -> str

Query cloud bucket.

Purpose

Answers a question using supported objects in a Google Cloud Storage bucket through the exact Gemini CloudBuckets search contract.

Parameters:

Name Type Description Default
bucket_name str

Required Google Cloud Storage bucket name.

required
query str

Required question about bucket content.

required

Returns:

Name Type Description
str str

Gemini answer grounded in supported bucket objects.

Source code in app.py
def query_cloud_bucket( bucket_name: str, query: str, ) -> str:
	"""Query cloud bucket.

	Purpose:
	    Answers a question using supported objects in a Google Cloud Storage bucket through
	    the exact Gemini CloudBuckets search contract.

	Args:
	    bucket_name (str): Required Google Cloud Storage bucket name.
	    query (str): Required question about bucket content.

	Returns:
	    str: Gemini answer grounded in supported bucket objects.
	"""
	throw_if( 'bucket_name', bucket_name, )
	throw_if( 'query', query, )

	model = str( st.session_state.get( 'bucket_model', '', ) or '' ).strip( )
	throw_if( 'model', model, )

	result = buckets.search( bucket=bucket_name, query=query, model=model,
		project_id=str( st.session_state.get( 'bucket_project_id', '', ) or '' ), location=str(
			st.session_state.get( 'bucket_location', 'us-central1', ) or 'us-central1' ),
		prefix=str( st.session_state.get( 'bucket_prefix', '', ) or '' ),
		max_files=int( st.session_state.get( 'bucket_max_files', 20, ) or 20 ),
		temperature=float( st.session_state.get( 'bucket_temperature', 0.0, ) or 0.0 ),
		top_p=float( st.session_state.get( 'bucket_top_percent', 0.0, ) or 0.0 ),
		frequency=float( st.session_state.get( 'bucket_frequency_penalty', 0.0, ) or 0.0 ),
		presence=float( st.session_state.get( 'bucket_presence_penalty', 0.0, ) or 0.0 ),
		max_tokens=int( st.session_state.get( 'bucket_max_tokens', 0, ) or 0 ),
		response_format=str( st.session_state.get( 'bucket_response_format', '', ) or '' ),
		instruct=str( st.session_state.get( 'bucket_system_instructions', '', ) or '' ), )

	if isinstance( result, str, ):
		return result.strip( )

	return str( getattr( buckets, 'output_text', '', ) or result or '' ).strip( )

get_prompt_connection

get_prompt_connection() -> Connection

Get prompt connection.

Purpose

Creates a SQLite connection to the configured application database for Prompt Engineering read and write operations.

Returns:

Type Description
Connection

sqlite3.Connection: Open SQLite connection to the application database.

Source code in app.py
def get_prompt_connection( ) -> sqlite3.Connection:
	"""Get prompt connection.

	Purpose:
	    Creates a SQLite connection to the configured application database for Prompt
	    Engineering read and write operations.

	Returns:
	    sqlite3.Connection: Open SQLite connection to the application database.
	"""
	return sqlite3.connect( cfg.DB_PATH )

reset_prompt_page

reset_prompt_page() -> None

Reset prompt page.

Purpose

Returns the Prompt Engineering result grid to its first page when a search or sort control changes.

Returns:

Name Type Description
None None

This function performs its work through side effects and does not return a value.

Source code in app.py
def reset_prompt_page( ) -> None:
	"""Reset prompt page.

	Purpose:
	    Returns the Prompt Engineering result grid to its first page when a search or sort
	    control changes.

	Returns:
	    None: This function performs its work through side effects and does not return a value.
	"""
	st.session_state[ 'pe_page' ] = 1

reset_prompt_selection

reset_prompt_selection() -> None

Reset prompt selection.

Purpose

Clears the selected Prompt Engineering record and resets the authoritative editor fields without changing search, sorting, or paging controls.

Returns:

Name Type Description
None None

This function performs its work through side effects and does not return a value.

Source code in app.py
def reset_prompt_selection( ) -> None:
	"""Reset prompt selection.

	Purpose:
	    Clears the selected Prompt Engineering record and resets the authoritative editor
	    fields without changing search, sorting, or paging controls.

	Returns:
	    None: This function performs its work through side effects and does not return a value.
	"""
	st.session_state[ 'pe_selected_id' ] = None
	st.session_state[ 'pe_caption' ] = ''
	st.session_state[ 'pe_name' ] = ''
	st.session_state[ 'pe_category' ] = None
	st.session_state[ 'pe_prompt' ] = ''

load_prompt_record

load_prompt_record(prompt_id: int) -> None

Load prompt record.

Purpose

Loads the selected category-aware prompt record into the authoritative Prompt Engineering editor fields.

Parameters:

Name Type Description Default
prompt_id int

Numeric primary key of the prompt record to load.

required

Returns:

Name Type Description
None None

This function performs its work through side effects and does not return a value.

Raises:

Type Description
Exception

Re-raises exceptions after recording them with the application logger.

Source code in app.py
def load_prompt_record( prompt_id: int ) -> None:
	"""Load prompt record.

	Purpose:
	    Loads the selected category-aware prompt record into the authoritative Prompt
	    Engineering editor fields.

	Args:
	    prompt_id (int): Numeric primary key of the prompt record to load.

	Returns:
	    None: This function performs its work through side effects and does not return a value.

	Raises:
	    Exception: Re-raises exceptions after recording them with the application logger.
	"""
	try:
		record = fetch_prompt_by_id( int( prompt_id ) )

		if record is None:
			reset_prompt_selection( )
			st.warning( f'Prompt {prompt_id} was not found.' )
			return

		st.session_state[ 'pe_selected_id' ] = int( record[ 'ID' ] )
		st.session_state[ 'pe_caption' ] = str( record[ 'Caption' ] )
		st.session_state[ 'pe_name' ] = str( record[ 'Name' ] )
		st.session_state[ 'pe_category' ] = str( record[ 'Category' ] )
		st.session_state[ 'pe_prompt' ] = str( record[ 'Prompt' ] )
	except Exception as e:
		ex = Error( e )
		ex.module = 'app'
		ex.cause = 'Prompt Engineering'
		ex.method = 'load_prompt_record( prompt_id: int ) -> None'
		Logger( ).write( ex )
		raise ex

fetch_prompt_editor_categories

fetch_prompt_editor_categories() -> List[str]

Fetch prompt editor categories.

Purpose

Returns the combined set of configured and persisted prompt categories available to the Prompt Engineering editor.

Returns:

Type Description
List[str]

List[str]: Sorted prompt categories available for record creation and editing.

Raises:

Type Description
Exception

Re-raises exceptions after recording them with the application logger.

Source code in app.py
def fetch_prompt_editor_categories( ) -> List[ str ]:
	"""Fetch prompt editor categories.

	Purpose:
	    Returns the combined set of configured and persisted prompt categories available to
	    the Prompt Engineering editor.

	Returns:
	    List[str]: Sorted prompt categories available for record creation and editing.

	Raises:
	    Exception: Re-raises exceptions after recording them with the application logger.
	"""
	try:
		configured_categories = { category for categories in PROMPT_CATEGORY_MODE_MAP.values( )
			for category in categories if isinstance( category, str ) and category.strip( ) }

		with get_prompt_connection( ) as conn:
			rows = conn.execute( f"""
				SELECT DISTINCT Category
				FROM {TABLE}
				WHERE Category IS NOT NULL
					AND TRIM(Category) <> '';
				""" ).fetchall( )

		persisted_categories = { str( row[ 0 ] ).strip( ) for row in rows if
			row and row[ 0 ] is not None and str( row[ 0 ] ).strip( ) }

		return sorted( configured_categories | persisted_categories )
	except Exception as e:
		ex = Error( e )
		ex.module = 'app'
		ex.cause = 'Prompt Engineering'
		ex.method = 'fetch_prompt_editor_categories( ) -> List[ str ]'
		Logger( ).write( ex )
		raise ex

validate_prompt_editor

validate_prompt_editor() -> Dict[str, str]

Validate prompt editor.

Purpose

Validates and normalizes the authoritative Prompt Engineering editor values before a prompt record is inserted or updated.

Returns:

Type Description
Dict[str, str]

Dict[str, str]: Normalized Caption, Name, Category, and Prompt values.

Raises:

Type Description
ValueError

Raised when a required prompt field is empty.

Source code in app.py
def validate_prompt_editor( ) -> Dict[ str, str ]:
	"""Validate prompt editor.

	Purpose:
	    Validates and normalizes the authoritative Prompt Engineering editor values before a
	    prompt record is inserted or updated.

	Returns:
	    Dict[str, str]: Normalized Caption, Name, Category, and Prompt values.

	Raises:
	    ValueError: Raised when a required prompt field is empty.
	"""
	data = { 'Caption': str( st.session_state.get( 'pe_caption', '' ) or '' ).strip( ),
		'Name': str( st.session_state.get( 'pe_name', '' ) or '' ).strip( ),
		'Category': str( st.session_state.get( 'pe_category', '' ) or '' ).strip( ),
		'Prompt': str( st.session_state.get( 'pe_prompt', '' ) or '' ).strip( ), }

	for field_name, field_value in data.items( ):
		if not field_value:
			raise ValueError( f'{field_name} is required.' )

	return data

save_prompt_record

save_prompt_record() -> None

Save prompt record.

Purpose

Creates or updates the authoritative Prompt Engineering record using the canonical category-aware prompt schema.

Returns:

Name Type Description
None None

This function performs its work through side effects and does not return a value.

Raises:

Type Description
Exception

Re-raises exceptions after recording them with the application logger.

Source code in app.py
def save_prompt_record( ) -> None:
	"""Save prompt record.

	Purpose:
	    Creates or updates the authoritative Prompt Engineering record using the canonical
	    category-aware prompt schema.

	Returns:
	    None: This function performs its work through side effects and does not return a value.

	Raises:
	    Exception: Re-raises exceptions after recording them with the application logger.
	"""
	try:
		data = validate_prompt_editor( )
		selected_id = st.session_state.get( 'pe_selected_id' )

		if selected_id is None:
			insert_prompt( data )
			message = 'Prompt created.'
		else:
			update_prompt( int( selected_id ), data )
			message = 'Prompt updated.'

		reset_prompt_selection( )
		st.success( message )
		st.rerun( )
	except ValueError as e:
		st.warning( str( e ) )
	except Exception as e:
		ex = Error( e )
		ex.module = 'app'
		ex.cause = 'Prompt Engineering'
		ex.method = 'save_prompt_record( ) -> None'
		Logger( ).write( ex )
		raise ex

delete_prompt_record

delete_prompt_record() -> None

Delete prompt record.

Purpose

Deletes the selected Prompt Engineering record and resets the authoritative editor state.

Returns:

Name Type Description
None None

This function performs its work through side effects and does not return a value.

Raises:

Type Description
Exception

Re-raises exceptions after recording them with the application logger.

Source code in app.py
def delete_prompt_record( ) -> None:
	"""Delete prompt record.

	Purpose:
	    Deletes the selected Prompt Engineering record and resets the authoritative editor
	    state.

	Returns:
	    None: This function performs its work through side effects and does not return a value.

	Raises:
	    Exception: Re-raises exceptions after recording them with the application logger.
	"""
	try:
		selected_id = st.session_state.get( 'pe_selected_id' )

		if selected_id is None:
			st.warning( 'Select a prompt before deleting.' )
			return

		delete_prompt( int( selected_id ) )
		reset_prompt_selection( )
		st.success( 'Prompt deleted.' )
		st.rerun( )
	except Exception as e:
		ex = Error( e )
		ex.module = 'app'
		ex.cause = 'Prompt Engineering'
		ex.method = 'delete_prompt_record( ) -> None'
		Logger( ).write( ex )
		raise ex

convert_prompt_xml_to_markdown

convert_prompt_xml_to_markdown() -> None

Convert prompt XML to Markdown.

Purpose

Converts XML-style instruction blocks in the authoritative prompt editor to Markdown.

Returns:

Name Type Description
None None

This function performs its work through side effects and does not return a value.

Source code in app.py
def convert_prompt_xml_to_markdown( ) -> None:
	"""Convert prompt XML to Markdown.

	Purpose:
	    Converts XML-style instruction blocks in the authoritative prompt editor to Markdown.

	Returns:
	    None: This function performs its work through side effects and does not return a value.
	"""
	prompt_value = st.session_state.get( 'pe_prompt', '' )

	if isinstance( prompt_value, str ) and prompt_value.strip( ):
		st.session_state[ 'pe_prompt' ] = convert_xml( prompt_value )

convert_prompt_markdown_to_xml

convert_prompt_markdown_to_xml() -> None

Convert prompt Markdown to XML.

Purpose

Converts Markdown headings in the authoritative prompt editor to XML-style instruction blocks.

Returns:

Name Type Description
None None

This function performs its work through side effects and does not return a value.

Source code in app.py
def convert_prompt_markdown_to_xml( ) -> None:
	"""Convert prompt Markdown to XML.

	Purpose:
	    Converts Markdown headings in the authoritative prompt editor to XML-style instruction
	    blocks.

	Returns:
	    None: This function performs its work through side effects and does not return a value.
	"""
	prompt_value = st.session_state.get( 'pe_prompt', '' )

	if isinstance( prompt_value, str ) and prompt_value.strip( ):
		st.session_state[ 'pe_prompt' ] = convert_markdown( prompt_value )