Skip to content

User Interface

Purpose

This page documents the main Gipity UI application at a high level.

app.py is the application entry point. It coordinates the user interface, workflow selection, session state, file upload handling, local document processing, result rendering, token tracking, and calls into the provider wrappers.

Responsibilities

app.py is responsible for:

  • Creating the Streamlit application shell.
  • Initializing session state.
  • Loading configuration values.
  • Rendering mode-specific controls.
  • Coordinating text, image, audio, embeddings, document, file, vector-store, prompt, and data workflows.
  • Handling uploaded files.
  • Rendering results and metrics.
  • Tracking token usage where supported.
  • Connecting the interface to provider wrappers in gpt.py.

Import-Safety Notice

This page intentionally does not use a mkdocstrings directive for app.py.

The main application module performs Streamlit-oriented setup and state initialization. Since mkdocstrings imports modules during documentation generation, importing the Streamlit runtime module can cause documentation build failures or side effects.

Current Documentation Strategy

The documentation site uses mkdocstrings for:

::: config
::: gpt

The documentation site describes app.py manually.

Build Guidance

If the documentation build fails after adding app, remove that directive and keep this manual page.

The safe initial API documentation targets are:

  • config.py
  • gpt.py

API Reference

app


Assembly:                Gipity
Filename:                name.py
Author:                  Terry D. Eppler
Created:                 05-31-2022

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

       app.py
       Copyright ©  2024  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

insert_data module-attribute

insert_data = {}

Insert data.

Purpose

Provides the insert data helper used by the Gipity Streamlit application. The function supports UI state management, provider coordination, data normalization, or display behavior required by the surrounding workflow.

Parameters:

Name Type Description Default
table_name str

Value supplied to the helper.

required
df DataFrame

Value supplied to the helper.

required

load_embedder

load_embedder() -> SentenceTransformer

Load embedder.

Purpose

Loads the embedder resource or state required by the Gipity workflow and returns the prepared value for caller use.

Returns:

Type Description
SentenceTransformer

Value produced by the load_embedder helper according to its function annotation and

SentenceTransformer

return statements.

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

        Purpose:
            Loads the embedder resource or state required by the Gipity workflow and returns the
            prepared value for caller use.

        Returns:
            Value produced by the load_embedder helper according to its function annotation and
            return statements.
    """
	return SentenceTransformer( 'all-MiniLM-L6-v2' )

throw_if

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

Throw if.

Purpose

Provides the throw if helper used by the Gipity Streamlit application. The function supports UI state management, provider coordination, data normalization, or display behavior required by the surrounding workflow.

Parameters:

Name Type Description Default
name str

Value supplied to the helper.

required
value object

Value supplied to the helper.

required

Raises:

Type Description
Error

Re-raised after the exception is wrapped and written to the application logger.

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

        Purpose:
            Provides the throw if helper used by the Gipity Streamlit application. The function
            supports UI state management, provider coordination, data normalization, or display
            behavior required by the surrounding workflow.

        Args:
            name (str): Value supplied to the helper.
            value (object): Value supplied to the helper.

        Raises:
            Error: Re-raised after the exception is wrapped and written to the application logger.
    """
	if value is None:
		raise ValueError( f'Argument "{name}" cannot be empty!' )
	if isinstance( value, str ) and (not value.strip( )):
		raise ValueError( f'Argument "{name}" cannot be empty!' )
	if isinstance( value, (list, tuple, dict, set) ) and len( value ) == 0:
		raise ValueError( f'Argument "{name}" cannot be empty!' )

extract_usage

extract_usage(resp: Any) -> Dict[str, int]

Extract usage.

Purpose

Extracts token usage from OpenAI Responses API and legacy completion response objects. The function normalizes current input and output token fields into the application-facing prompt, completion, and total token schema used by existing Streamlit metrics.

Parameters:

Name Type Description Default
resp Any

OpenAI response object or dictionary containing a usage payload.

required

Returns:

Type Description
Dict[str, int]

Dict[ str, int ]: Normalized prompt, completion, and total token counts.

Source code in app.py
def extract_usage( resp: Any ) -> Dict[ str, int ]:
	"""Extract usage.

	Purpose:
		Extracts token usage from OpenAI Responses API and legacy completion response objects.
		The function normalizes current input and output token fields into the application-facing
		prompt, completion, and total token schema used by existing Streamlit metrics.

	Args:
		resp (Any): OpenAI response object or dictionary containing a usage payload.

	Returns:
		Dict[ str, int ]: Normalized prompt, completion, and total token counts.
	"""
	throw_if( 'resp', resp )
	usage = {
			'prompt_tokens': 0,
			'completion_tokens': 0,
			'total_tokens': 0, }

	raw = None

	try:
		raw = getattr( resp, 'usage', None )
	except Exception as e:
		exception = Error( e )
		exception.module = 'app'
		exception.cause = 'extract_usage'
		exception.method = 'extract_usage( resp: Any ) -> Dict[ str, int ]'
		Logger( ).write( exception )
		raw = None

	if raw is None and isinstance( resp, dict ):
		raw = resp.get( 'usage' )

	if raw is None:
		return usage

	try:
		if isinstance( raw, dict ):
			usage[ 'prompt_tokens' ] = raw.get( 'input_tokens', raw.get( 'prompt_tokens', 0 ) )
			usage[ 'completion_tokens' ] = int(
				raw.get( 'output_tokens', raw.get( 'completion_tokens', 0 ) ) or 0 )

			usage[ 'total_tokens' ] = int( raw.get( 'total_tokens',
				usage[ 'prompt_tokens' ] + usage[ 'completion_tokens' ], ) or 0 )
		else:
			usage[ 'prompt_tokens' ] = int(
				getattr( raw, 'input_tokens', getattr( raw, 'prompt_tokens', 0 ), ) or 0 )

			usage[ 'completion_tokens' ] = int(
				getattr( raw, 'output_tokens', getattr( raw, 'completion_tokens', 0 ), ) or 0 )

			usage[ 'total_tokens' ] = int( getattr( raw, 'total_tokens',
				usage[ 'prompt_tokens' ] + usage[ 'completion_tokens' ], ) or 0 )
	except Exception as e:
		exception = Error( e )
		exception.module = 'app'
		exception.cause = 'extract_usage'
		exception.method = 'extract_usage( resp: Any ) -> Dict[ str, int ]'
		Logger( ).write( exception )
		usage[ 'total_tokens' ] = usage[ 'prompt_tokens' ] + usage[ 'completion_tokens' ]

	return usage

update_token_counters

update_token_counters(resp: Any) -> None

Update token counters.

Purpose

Updates the token counters state or persisted value used by the Gipity workflow.

Parameters:

Name Type Description Default
resp Any

Value supplied to the helper.

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

        Purpose:
            Updates the token counters state or persisted value used by the Gipity workflow.

        Args:
            resp (Any): Value supplied to the helper.
    """
	throw_if( 'resp', resp )
	usage = extract_usage( 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 )

extract_response_text

extract_response_text(response: object) -> str

Extract response text.

Purpose

Extracts the response text value from the supplied object or payload while handling missing or unsupported content safely.

Parameters:

Name Type Description Default
response object

Value supplied to the helper.

required

Returns:

Type Description
str

Value produced by the extract_response_text helper according to its function annotation

str

and return statements.

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

        Purpose:
            Extracts the response text value from the supplied object or payload while handling
            missing or unsupported content safely.

        Args:
            response (object): Value supplied to the helper.

        Returns:
            Value produced by the extract_response_text helper according to its function annotation
            and return statements.
    """
	throw_if( 'respose', response )
	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

encode_image(image_path: str) -> str

Encode image.

Purpose

Provides the encode image helper used by the Gipity Streamlit application. The function supports UI state management, provider coordination, data normalization, or display behavior required by the surrounding workflow.

Parameters:

Name Type Description Default
image_path str

Value supplied to the helper.

required

Returns:

Type Description
str

Value produced by the encode_image helper according to its function annotation and

str

return statements.

Source code in app.py
def encode_image( image_path: str ) -> str:
	"""Encode image.

        Purpose:
            Provides the encode image helper used by the Gipity Streamlit application. The function
            supports UI state management, provider coordination, data normalization, or display
            behavior required by the surrounding workflow.

        Args:
            image_path (str): Value supplied to the helper.

        Returns:
            Value produced by the encode_image helper according to its function annotation and
            return statements.
    """
	throw_if( 'image_path', image_path )
	with open( image_path, 'rb' ) as image_file:
		return base64.b64encode( image_file.read( ) ).decode( 'utf-8' )

normalize_text

normalize_text(text: str) -> str

Normalize text.

Purpose

Normalizes the text input into the stable shape expected by downstream Gipity helpers and display logic.

Parameters:

Name Type Description Default
text str

Value supplied to the helper.

required

Returns:

Type Description
str

Value produced by the normalize_text helper according to its function annotation and

str

return statements.

Raises:

Type Description
Error

Re-raised after the exception is wrapped and written to the application logger.

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

        Purpose:
            Normalizes the text input into the stable shape expected by downstream Gipity helpers
            and display logic.

        Args:
            text (str): Value supplied to the helper.

        Returns:
            Value produced by the normalize_text helper according to its function annotation and
            return statements.

        Raises:
            Error: Re-raised after the exception is wrapped and written to the application logger.
    """
	try:
		throw_if( 'text', text )
		if not text:
			return ''
		text = text.lower( )
		text = re.sub( '[^\\w\\s\\.\\!\\?]', '', text )
		text = re.sub( '([.!?])\\s*', '\\1 ', text )
		text = re.sub( '\\s+', ' ', text ).strip( )
		return text
	except Exception as e:
		exception = Error( e )
		exception.module = 'app'
		exception.cause = 'normalize_text'
		exception.method = 'normalize_text( ... )'
		Logger( ).write( exception )
		raise e

chunk_text

chunk_text(text: str, max_tokens: int = 400) -> List[str]

Chunk text.

Purpose

Provides the chunk text helper used by the Gipity Streamlit application. The function supports UI state management, provider coordination, data normalization, or display behavior required by the surrounding workflow.

Parameters:

Name Type Description Default
text str

Value supplied to the helper.

required
max_tokens int

Value supplied to the helper.

400

Returns:

Type Description
List[str]

Value produced by the chunk_text helper according to its function annotation and return

List[str]

statements.

Source code in app.py
def chunk_text( text: str, max_tokens: int = 400 ) -> List[ str ]:
	"""Chunk text.

        Purpose:
            Provides the chunk text helper used by the Gipity Streamlit application. The function
            supports UI state management, provider coordination, data normalization, or display
            behavior required by the surrounding workflow.

        Args:
            text (str): Value supplied to the helper.
            max_tokens (int): Value supplied to the helper.

        Returns:
            Value produced by the chunk_text helper according to its function annotation and return
            statements.
    """
	if not text:
		return [ ]
	sentences = re.split( '(?<=[.!?])\\s+', text )
	sentences = [ s.strip( ) for s in sentences if s.strip( ) ]
	if len( sentences ) > 1:
		return sentences
	words = text.split( )
	chunks = [ ]
	current_chunk = [ ]
	token_count = 0
	for word in words:
		current_chunk.append( word )
		token_count += 1
		if token_count >= max_tokens:
			chunks.append( ' '.join( current_chunk ) )
			current_chunk = [ ]
			token_count = 0
	if current_chunk:
		chunks.append( ' '.join( current_chunk ) )
	return chunks

cosine_sim

cosine_sim(a: ndarray, b: ndarray) -> float

Cosine sim.

Purpose

Provides the cosine sim helper used by the Gipity Streamlit application. The function supports UI state management, provider coordination, data normalization, or display behavior required by the surrounding workflow.

Parameters:

Name Type Description Default
a ndarray

Value supplied to the helper.

required
b ndarray

Value supplied to the helper.

required

Returns:

Type Description
float

Value produced by the cosine_sim helper according to its function annotation and return

float

statements.

Source code in app.py
def cosine_sim( a: np.ndarray, b: np.ndarray ) -> float:
	"""Cosine sim.

        Purpose:
            Provides the cosine sim helper used by the Gipity Streamlit application. The function
            supports UI state management, provider coordination, data normalization, or display
            behavior required by the surrounding workflow.

        Args:
            a (np.ndarray): Value supplied to the helper.
            b (np.ndarray): Value supplied to the helper.

        Returns:
            Value produced by the cosine_sim helper according to its function annotation and return
            statements.
    """
	denom = np.linalg.norm( a ) * np.linalg.norm( b )
	return float( np.dot( a, b ) / denom ) if denom else 0.0

sanitize_markdown

sanitize_markdown(text: str) -> str

Sanitize markdown.

Purpose

Provides the sanitize markdown helper used by the Gipity Streamlit application. The function supports UI state management, provider coordination, data normalization, or display behavior required by the surrounding workflow.

Parameters:

Name Type Description Default
text str

Value supplied to the helper.

required

Returns:

Type Description
str

Value produced by the sanitize_markdown helper according to its function annotation and

str

return statements.

Raises:

Type Description
Error

Re-raised after the exception is wrapped and written to the application logger.

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

        Purpose:
            Provides the sanitize markdown helper used by the Gipity Streamlit application. The
            function supports UI state management, provider coordination, data normalization, or
            display behavior required by the surrounding workflow.

        Args:
            text (str): Value supplied to the helper.

        Returns:
            Value produced by the sanitize_markdown helper according to its function annotation and
            return statements.

        Raises:
            Error: Re-raised after the exception is wrapped and written to the application logger.
    """
	try:
		throw_if( 'text', text )
		text = re.sub( '\\*\\*(.*?)\\*\\*', '\\1', text )
		text = re.sub( '\\*(.*?)\\*', '\\1', text )
		return text
	except Exception as e:
		exception = Error( e )
		exception.module = 'app'
		exception.cause = 'sanitize_markdown'
		exception.method = 'sanitize_markdown( ... )'
		Logger( ).write( exception )
		raise e

init_state

init_state() -> None

Init state.

Purpose

Provides the init state helper used by the Gipity Streamlit application. The function supports UI state management, provider coordination, data normalization, or display behavior required by the surrounding workflow.

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

        Purpose:
            Provides the init state helper used by the Gipity Streamlit application. The function
            supports UI state management, provider coordination, data normalization, or display
            behavior required by the surrounding workflow.
    """
	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

Resets the state state used by the application. The function clears related Streamlit keys without performing provider calls.

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

        Purpose:
            Resets the state state used by the application. The function clears related Streamlit
            keys without performing provider calls.
    """
	st.session_state.chat_history = [ ]
	st.session_state.messages = [ ]
	st.session_state.last_answer = ''
	st.session_state.last_sources = [ ]

normalize

normalize(obj) -> Any

Normalize.

Purpose

Provides the normalize helper used by the Gipity Streamlit application. The function supports UI state management, provider coordination, data normalization, or display behavior required by the surrounding workflow.

Parameters:

Name Type Description Default
obj Any

Value supplied to the helper.

required

Returns:

Type Description
Any

Value produced by the normalize helper according to its function annotation and return

Any

statements.

Raises:

Type Description
Error

Re-raised after the exception is wrapped and written to the application logger.

Source code in app.py
def normalize( obj ) -> Any:
	"""Normalize.

        Purpose:
            Provides the normalize helper used by the Gipity Streamlit application. The function
            supports UI state management, provider coordination, data normalization, or display
            behavior required by the surrounding workflow.

        Args:
            obj (Any): Value supplied to the helper.

        Returns:
            Value produced by the normalize helper according to its function annotation and return
            statements.

        Raises:
            Error: Re-raised after the exception is wrapped and written to the application logger.
    """
	try:
		throw_if( 'obj', obj )
		if obj is None or isinstance( obj, (str, int, float, bool) ):
			return obj
		if isinstance( obj, dict ):
			return { k: normalize( v ) for k, v in obj.items( ) }
		if isinstance( obj, (list, tuple, set) ):
			return [ normalize( v ) for v in obj ]
		if hasattr( obj, 'model_dump' ):
			try:
				return obj.model_dump( )
			except Exception as e:
				exception = Error( e )
				exception.module = 'app'
				exception.cause = 'normalize'
				exception.method = 'normalize( ... )'
				Logger( ).write( exception )
				return str( obj )
		return str( obj )
	except Exception as e:
		exception = Error( e )
		exception.module = 'app'
		exception.cause = 'normalize'
		exception.method = 'normalize( ... )'
		Logger( ).write( exception )
		raise e

save_temp

save_temp(upload) -> str | None

Save temp.

Purpose

Saves the temp value for later workflow use while preserving the caller-facing return contract.

Parameters:

Name Type Description Default
upload Any

Value supplied to the helper.

required

Returns:

Type Description
str | None

Value produced by the save_temp helper according to its function annotation and return

str | None

statements.

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

        Purpose:
            Saves the temp value for later workflow use while preserving the caller-facing return
            contract.

        Args:
            upload (Any): Value supplied to the helper.

        Returns:
            Value produced by the save_temp helper according to its function annotation and return
            statements.
    """
	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 as e:
		exception = Error( e )
		exception.module = 'app'
		exception.cause = 'save_temp'
		exception.method = 'save_temp( ... )'
		Logger( ).write( exception )
		return None

display_value

display_value(val: Any) -> str

Display value.

Purpose

Provides the display value helper used by the Gipity Streamlit application. The function supports UI state management, provider coordination, data normalization, or display behavior required by the surrounding workflow.

Parameters:

Name Type Description Default
val Any

Value supplied to the helper.

required

Returns:

Type Description
str

Value produced by the display_value helper according to its function annotation and

str

return statements.

Source code in app.py
def display_value( val: Any ) -> str:
	"""Display value.

        Purpose:
            Provides the display value helper used by the Gipity Streamlit application. The function
            supports UI state management, provider coordination, data normalization, or display
            behavior required by the surrounding workflow.

        Args:
            val (Any): Value supplied to the helper.

        Returns:
            Value produced by the display_value helper according to its function annotation and
            return statements.
    """
	if val is None:
		return '—'
	try:
		return str( val )
	except Exception as e:
		exception = Error( e )
		exception.module = 'app'
		exception.cause = 'display_value'
		exception.method = 'display_value( ... )'
		Logger( ).write( exception )
		return '—'

format_results

format_results(results) -> str

Format results.

Purpose

Provides the format results helper used by the Gipity Streamlit application. The function supports UI state management, provider coordination, data normalization, or display behavior required by the surrounding workflow.

Parameters:

Name Type Description Default
results Any

Value supplied to the helper.

required

Returns:

Type Description
str

Value produced by the format_results helper according to its function annotation and

str

return statements.

Source code in app.py
def format_results( results ) -> str:
	"""Format results.

        Purpose:
            Provides the format results helper used by the Gipity Streamlit application. The
            function supports UI state management, provider coordination, data normalization, or
            display behavior required by the surrounding workflow.

        Args:
            results (Any): Value supplied to the helper.

        Returns:
            Value produced by the format_results helper according to its function annotation and
            return statements.
    """
	formatted_results = ''
	for result in results.data:
		formatted_result = f'<li> "{result.name}" '
		formatted_results += formatted_result + '</li>'
	return f'<p>{formatted_results}</p>'

count_tokens

count_tokens(text: str) -> int

Count tokens.

Purpose

Provides the count tokens helper used by the Gipity Streamlit application. The function supports UI state management, provider coordination, data normalization, or display behavior required by the surrounding workflow.

Parameters:

Name Type Description Default
text str

Value supplied to the helper.

required

Returns:

Type Description
int

Value produced by the count_tokens helper according to its function annotation and

int

return statements.

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

        Purpose:
            Provides the count tokens helper used by the Gipity Streamlit application. The function
            supports UI state management, provider coordination, data normalization, or display
            behavior required by the surrounding workflow.

        Args:
            text (str): Value supplied to the helper.

        Returns:
            Value produced by the count_tokens helper according to its function annotation and
            return statements.
    """
	encoding = tiktoken.get_encoding( 'cl100k_base' )
	num_tokens = len( encoding.encode( text ) )
	return num_tokens

convert_xml

convert_xml(text: str) -> str

Convert xml.

Purpose

Provides the convert xml helper used by the Gipity Streamlit application. The function supports UI state management, provider coordination, data normalization, or display behavior required by the surrounding workflow.

Parameters:

Name Type Description Default
text str

Value supplied to the helper.

required

Returns:

Type Description
str

Value produced by the convert_xml helper according to its function annotation and return

str

statements.

Raises:

Type Description
Error

Re-raised after the exception is wrapped and written to the application logger.

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

        Purpose:
            Provides the convert xml helper used by the Gipity Streamlit application. The function
            supports UI state management, provider coordination, data normalization, or display
            behavior required by the surrounding workflow.

        Args:
            text (str): Value supplied to the helper.

        Returns:
            Value produced by the convert_xml helper according to its function annotation and return
            statements.

        Raises:
            Error: Re-raised after the exception is wrapped and written to the application logger.
    """
	try:
		throw_if( 'text', text )
		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( )
			heading: str = raw_tag.replace( '_', ' ' ).replace( '-', ' ' ).title( )
			markdown_blocks.append( f'## {heading}' )
			if body:
				markdown_blocks.append( body )
		return '\n\n'.join( markdown_blocks )
	except Exception as e:
		exception = Error( e )
		exception.module = 'app'
		exception.cause = 'convert_xml'
		exception.method = 'convert_xml( ... )'
		Logger( ).write( exception )
		raise e

convert_markdown

convert_markdown(text: Any) -> str

Convert markdown.

Purpose

Provides the convert markdown helper used by the Gipity Streamlit application. The function supports UI state management, provider coordination, data normalization, or display behavior required by the surrounding workflow.

Parameters:

Name Type Description Default
text Any

Value supplied to the helper.

required

Returns:

Type Description
str

Value produced by the convert_markdown helper according to its function annotation and

str

return statements.

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

        Purpose:
            Provides the convert markdown helper used by the Gipity Streamlit application. The
            function supports UI state management, provider coordination, data normalization, or
            display behavior required by the surrounding workflow.

        Args:
            text (Any): Value supplied to the helper.

        Returns:
            Value produced by the convert_markdown helper according to its function annotation and
            return statements.
    """
	if not isinstance( text, str ) or not text.strip( ):
		return ''
	src = text.replace( '\r\n', '\n' ).replace( '\r', '\n' )
	htag_pattern = re.compile( '<h([1-6])>(.*?)</h\\1>', flags=re.IGNORECASE | re.DOTALL )
	md_heading_pattern = re.compile( '^(#{1,6})[ \\t]+(.+?)[ \\t]*$', flags=re.MULTILINE )
	contains_htags = bool( htag_pattern.search( src ) )
	if contains_htags:
		def _htag_to_md( match: re.Match ) -> str:
			"""Htag to md.

                Purpose:
                    Provides the htag to md helper used by the Gipity Streamlit application. The function
                    supports UI state management, provider coordination, data normalization, or display
                    behavior required by the surrounding workflow.

                Args:
                    match (re.Match): Value supplied to the helper.

                Returns:
                    Value produced by the _htag_to_md helper according to its function annotation and return
                    statements.
            """
			level = int( match.group( 1 ) )
			content = match.group( 2 ).strip( )
			content = re.sub( '[ \\t]+\\n', '\n', content )
			content = re.sub( '\\n[ \\t]+', '\n', content )
			return f"{'#' * level} {content}"

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

	def _md_to_htag( match: re.Match ) -> str:
		"""Md to htag.

            Purpose:
                Provides the md to htag helper used by the Gipity Streamlit application. The function
                supports UI state management, provider coordination, data normalization, or display
                behavior required by the surrounding workflow.

            Args:
                match (re.Match): Value supplied to the helper.

            Returns:
                Value produced by the _md_to_htag helper according to its function annotation and return
                statements.
        """
		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

Provides the inject response css helper used by the Gipity Streamlit application. The function supports UI state management, provider coordination, data normalization, or display behavior required by the surrounding workflow.

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

        Purpose:
            Provides the inject response css helper used by the Gipity Streamlit application. The
            function supports UI state management, provider coordination, data normalization, or
            display behavior required by the surrounding workflow.
    """
	st.markdown(
		'\n\t\t<style>\n\t\t/* Chat message text */\n\t\t.stChatMessage p {\n\t\t\tcolor: rgb(220, 220, 220);\n\t\t\tfont-size: 1rem;\n\t\t\tline-height: 1.6;\n\t\t}\n\n\t\t/* Headings inside chat responses */\n\t\t.stChatMessage h1 {\n\t\t\tcolor: rgb(0, 120, 252); /* DoD Blue */\n\t\t\tfont-size: 1.6rem;\n\t\t}\n\n\t\t.stChatMessage h2 {\n\t\t\tcolor: rgb(0, 120, 252);\n\t\t\tfont-size: 1.35rem;\n\t\t}\n\n\t\t.stChatMessage h3 {\n\t\t\tcolor: rgb(0, 120, 252);\n\t\t\tfont-size: 1.15rem;\n\t\t}\n\t\t\n\t\t.stChatMessage a {\n\t\t\tcolor: rgb(0, 120, 252); /* DoD Blue */\n\t\t\ttext-decoration: underline;\n\t\t}\n\t\t\n\t\t.stChatMessage a:hover {\n\t\t\tcolor: rgb(80, 160, 255);\n\t\t}\n\n\t\t</style>\n\t\t',
		unsafe_allow_html=True )

style_subheaders

style_subheaders() -> None

Style subheaders.

Purpose

Provides the style subheaders helper used by the Gipity Streamlit application. The function supports UI state management, provider coordination, data normalization, or display behavior required by the surrounding workflow.

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

        Purpose:
            Provides the style subheaders helper used by the Gipity Streamlit application. The
            function supports UI state management, provider coordination, data normalization, or
            display behavior required by the surrounding workflow.
    """
	st.markdown(
		'\n\t\t<style>\n\t\tdiv[data-testid="stMarkdownContainer"] h2,\n\t\tdiv[data-testid="stMarkdownContainer"] h3,\n\t\tdiv[data-testid="stChatMessage"] div[data-testid="stMarkdownContainer"] h2,\n\t\tdiv[data-testid="stChatMessage"] div[data-testid="stMarkdownContainer"] h3 {\n\t\t\tcolor: rgb(0, 120, 252) !important;\n\t\t}\n\t\t</style>\n\t\t',
		unsafe_allow_html=True )

save_message

save_message(role: str, content: str) -> None

Save message.

Purpose

Saves the message value for later workflow use while preserving the caller-facing return contract.

Parameters:

Name Type Description Default
role str

Value supplied to the helper.

required
content str

Value supplied to the helper.

required
Source code in app.py
def save_message( role: str, content: str ) -> None:
	"""Save message.

        Purpose:
            Saves the message value for later workflow use while preserving the caller-facing return
            contract.

        Args:
            role (str): Value supplied to the helper.
            content (str): Value supplied to the helper.
    """
	with sqlite3.connect( cfg.DB_PATH ) as conn:
		conn.execute( 'INSERT INTO chat_history (role, content) VALUES (?, ?)', (role, content) )

load_history

load_history() -> List[Tuple[str, str]]

Load history.

Purpose

Loads the history resource or state required by the Gipity workflow and returns the prepared value for caller use.

Returns:

Type Description
List[Tuple[str, str]]

Value produced by the load_history helper according to its function annotation and

List[Tuple[str, str]]

return statements.

Source code in app.py
def load_history( ) -> List[ Tuple[ str, str ] ]:
	"""Load history.

        Purpose:
            Loads the history resource or state required by the Gipity workflow and returns the
            prepared value for caller use.

        Returns:
            Value produced by the load_history helper according to its function annotation and
            return statements.
    """
	with sqlite3.connect( cfg.DB_PATH ) as conn:
		return conn.execute( 'SELECT role, content FROM chat_history ORDER BY id' ).fetchall( )

clear_history

clear_history() -> None

Clear history.

Purpose

Clears the history state used by the current workflow so the user interface can start from a clean output state.

Source code in app.py
def clear_history( ) -> None:
	"""Clear history.

        Purpose:
            Clears the history state used by the current workflow so the user interface can start
            from a clean output state.
    """
	with sqlite3.connect( cfg.DB_PATH ) as conn:
		conn.execute( 'DELETE FROM chat_history' )

extract_sources

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

Extract sources.

Purpose

Extracts web-search and file-search source metadata from an OpenAI Responses API response. The function preserves the application-facing source schema while mapping provider file search results to the correct singular file identifier field.

Parameters:

Name Type Description Default
response Any

OpenAI Responses API response object.

required

Returns:

Type Description
List[Dict[str, Any]]

List[ Dict[ str, Any ] ]: Normalized source metadata used by the application.

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

	Purpose:
		Extracts web-search and file-search source metadata from an OpenAI Responses API response.
		The function preserves the application-facing source schema while mapping provider file
		search results to the correct singular file identifier field.

	Args:
		response (Any): OpenAI Responses API response object.

	Returns:
		List[ Dict[ str, Any ] ]: Normalized source metadata used by the application.
	"""
	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

		item_type = getattr( item, 'type', None )
		if item_type == 'web_search_call':
			action = getattr( item, 'action', None )
			raw_sources = getattr( action, 'sources', None ) if action else None
			if not isinstance( raw_sources, (list, tuple) ):
				continue

			for raw_source in raw_sources:
				source = normalize( raw_source )

				if not isinstance( source, dict ):
					continue

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

		elif item_type == 'file_search_call':
			raw_results = getattr( item, 'results', None )

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

			for raw_result in raw_results:
				result = normalize( raw_result )

				if not isinstance( result, dict ):
					continue

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

	return sources

ensure_text_mode_state

ensure_text_mode_state() -> None

Ensure text mode state.

Purpose

Ensures the required text mode state session-state keys or runtime resources exist before the related interface controls are rendered.

Source code in app.py
def ensure_text_mode_state( ) -> None:
	"""Ensure text mode state.

        Purpose:
            Ensures the required text mode state session-state keys or runtime resources exist
            before the related interface controls are rendered.
    """
	if 'text_vector_store_ids' not in st.session_state:
		st.session_state[ 'text_vector_store_ids' ] = ''
	if 'text_json_schema_name' not in st.session_state:
		st.session_state[ 'text_json_schema_name' ] = 'structured_response'
	if 'text_json_schema' not in st.session_state:
		st.session_state[ 'text_json_schema' ] = ''
	if 'text_json_schema_strict' not in st.session_state:
		st.session_state[ 'text_json_schema_strict' ] = True
	if 'text_conversation_id' not in st.session_state:
		st.session_state[ 'text_conversation_id' ] = ''
	if 'text_stream' not in st.session_state:
		st.session_state[ 'text_stream' ] = False
	if 'text_background' not in st.session_state:
		st.session_state[ 'text_background' ] = False

parse_text_vector_store_ids

parse_text_vector_store_ids(
    value: str | List[str] | None,
) -> List[str]

Parse text vector store ids.

Purpose

Provides the parse text vector store ids helper used by the Gipity Streamlit application. The function supports UI state management, provider coordination, data normalization, or display behavior required by the surrounding workflow.

Parameters:

Name Type Description Default
value str | List[str] | None

Value supplied to the helper.

required

Returns:

Type Description
List[str]

Value produced by the parse_text_vector_store_ids helper according to its function

List[str]

annotation and return statements.

Source code in app.py
def parse_text_vector_store_ids( value: str | List[ str ] | None ) -> List[ str ]:
	"""Parse text vector store ids.

        Purpose:
            Provides the parse text vector store ids helper used by the Gipity Streamlit
            application. The function supports UI state management, provider coordination, data
            normalization, or display behavior required by the surrounding workflow.

        Args:
            value (str | List[str] | None): Value supplied to the helper.

        Returns:
            Value produced by the parse_text_vector_store_ids helper according to its function
            annotation and return statements.
    """
	if value is None:
		return [ ]
	if isinstance( value, list ):
		return [ str( item ).strip( ) for item in value if str( item ).strip( ) ]
	if not isinstance( value, str ) or not value.strip( ):
		return [ ]
	return [ item.strip( ) for item in value.split( ',' ) if item.strip( ) ]

build_text_response_format

build_text_response_format(
    response_format: str | None,
    schema_name: str = None,
    schema_text: str = None,
    strict: bool = True,
) -> Dict[str, Any] | None

Build text response format.

Purpose

Builds the text response format value used by the Gipity interface or provider wrapper. The function normalizes inputs and returns a stable object for downstream use.

Parameters:

Name Type Description Default
response_format str | None

Value supplied to the helper.

required
schema_name str

Value supplied to the helper.

None
schema_text str

Value supplied to the helper.

None
strict bool

Value supplied to the helper.

True

Returns:

Type Description
Dict[str, Any] | None

Value produced by the build_text_response_format helper according to its function

Dict[str, Any] | None

annotation and return statements.

Source code in app.py
def build_text_response_format( response_format: str | None, schema_name: str = None,
		schema_text: str = None, strict: bool = True ) -> Dict[ str, Any ] | None:
	"""Build text response format.

        Purpose:
            Builds the text response format value used by the Gipity interface or provider wrapper.
            The function normalizes inputs and returns a stable object for downstream use.

        Args:
            response_format (str | None): Value supplied to the helper.
            schema_name (str): Value supplied to the helper.
            schema_text (str): Value supplied to the helper.
            strict (bool): Value supplied to the helper.

        Returns:
            Value produced by the build_text_response_format helper according to its function
            annotation and return statements.
    """
	if not isinstance( response_format, str ) or not response_format.strip( ):
		return None
	format_name = response_format.strip( )
	if format_name == 'text':
		return { 'format': { 'type': 'text' } }
	if format_name == 'json_object':
		return { 'format': { 'type': 'json_object' } }
	if format_name == 'json_schema':
		if not isinstance( schema_text, str ) or not schema_text.strip( ):
			st.warning( 'JSON Schema output requires a schema. Falling back to plain text.' )
			return { 'format': { 'type': 'text' } }
		try:
			schema = json.loads( schema_text )
		except Exception as exc:
			exception = Error( exc )
			exception.module = 'app'
			exception.cause = 'build_text_response_format'
			exception.method = 'build_text_response_format( ... )'
			Logger( ).write( exception )
			st.warning( f'JSON Schema could not be parsed. Falling back to plain text: {exc}' )
			return { 'format': { 'type': 'text' } }
		name = schema_name if isinstance( schema_name,
			str ) and schema_name.strip( ) else 'structured_response'
		return { 'format': { 'type': 'json_schema', 'name': name.strip( ), 'schema': schema,
		                     'strict': bool( strict ) } }
	return None

build_text_tools

build_text_tools(
    selected_tools: List[str] | None,
    vector_store_ids: List[str] = None,
) -> List[Dict[str, Any]]

Build text tools.

Purpose

Builds the text tools value used by the Gipity interface or provider wrapper. The function normalizes inputs and returns a stable object for downstream use.

Parameters:

Name Type Description Default
selected_tools List[str] | None

Value supplied to the helper.

required
vector_store_ids List[str]

Value supplied to the helper.

None

Returns:

Type Description
List[Dict[str, Any]]

Value produced by the build_text_tools helper according to its function annotation and

List[Dict[str, Any]]

return statements.

Source code in app.py
def build_text_tools( selected_tools: List[ str ] | None,
	vector_store_ids: List[ str ] = None ) ->  List[ Dict[ str, Any ] ]:
	"""Build text tools.

        Purpose:
            Builds the text tools value used by the Gipity interface or provider wrapper. The
            function normalizes inputs and returns a stable object for downstream use.

        Args:
            selected_tools (List[str] | None): Value supplied to the helper.
            vector_store_ids (List[str]): Value supplied to the helper.

        Returns:
            Value produced by the build_text_tools helper according to its function annotation and
            return statements.
    """
	tools: List[ Dict[ str, Any ] ] = [ ]
	vector_ids = vector_store_ids if vector_store_ids is not None else [ ]
	if selected_tools is None or len( selected_tools ) == 0:
		return tools
	for name in selected_tools:
		if not isinstance( name, str ) or not name.strip( ):
			continue
		tool_name = name.strip( )
		if tool_name == 'web_search':
			tools.append( { 'type': 'web_search' } )
			continue
		if tool_name == 'file_search':
			if len( vector_ids ) == 0:
				st.warning( 'File Search was selected, but no vector store IDs were provided.' )
				continue
			tools.append( { 'type': 'file_search' } )
			continue
	return tools

build_text_include

build_text_include(
    selected_include: List[str] | None,
    selected_tools: List[Dict[str, Any]] = None,
) -> List[str]

Build text include.

Purpose

Builds the text include value used by the Gipity interface or provider wrapper. The function normalizes inputs and returns a stable object for downstream use.

Parameters:

Name Type Description Default
selected_include List[str] | None

Value supplied to the helper.

required
selected_tools List[Dict[str, Any]]

Value supplied to the helper.

None

Returns:

Type Description
List[str]

Value produced by the build_text_include helper according to its function annotation and

List[str]

return statements.

Source code in app.py
def build_text_include( selected_include: List[ str ] | None,
		selected_tools: List[ Dict[ str, Any ] ] = None ) -> List[ str ]:
	"""Build text include.

        Purpose:
            Builds the text include value used by the Gipity interface or provider wrapper. The
            function normalizes inputs and returns a stable object for downstream use.

        Args:
            selected_include (List[str] | None): Value supplied to the helper.
            selected_tools (List[Dict[str, Any]]): Value supplied to the helper.

        Returns:
            Value produced by the build_text_include helper according to its function annotation and
            return statements.
    """
	if selected_include is None or len( selected_include ) == 0:
		return [ ]
	tool_types: List[ str ] = [ ]
	if isinstance( selected_tools, list ):
		for tool in selected_tools:
			if isinstance( tool, dict ) and tool.get( 'type' ):
				tool_types.append( str( tool.get( 'type' ) ) )
	include_values: List[ str ] = [ ]
	for value in selected_include:
		if not isinstance( value, str ) or not value.strip( ):
			continue
		include_name = value.strip( )
		if include_name == 'reasoning.encrypted_content':
			include_values.append( include_name )
			continue
		if include_name == 'message.output_text.logprobs':
			include_values.append( include_name )
			continue
		if include_name.startswith( 'web_search_call.' ) and 'web_search' in tool_types:
			include_values.append( include_name )
			continue
		if include_name == 'file_search_call.results' and 'file_search' in tool_types:
			include_values.append( include_name )
			continue
	return include_values

build_text_tool_choice

build_text_tool_choice(
    tool_choice: str | None,
    selected_tools: List[Dict[str, Any]] | None = None,
) -> str | None

Build text tool choice.

Purpose

Builds the text tool choice value used by the Gipity interface or provider wrapper. The function normalizes inputs and returns a stable object for downstream use.

Parameters:

Name Type Description Default
tool_choice str | None

Value supplied to the helper.

required
selected_tools List[Dict[str, Any]] | None

Value supplied to the helper.

None

Returns:

Type Description
str | None

Value produced by the build_text_tool_choice helper according to its function annotation

str | None

and return statements.

Source code in app.py
def build_text_tool_choice( tool_choice: str | None,
		selected_tools: List[ Dict[ str, Any ] ] | None = None ) -> str | None:
	"""Build text tool choice.

        Purpose:
            Builds the text tool choice value used by the Gipity interface or provider wrapper. The
            function normalizes inputs and returns a stable object for downstream use.

        Args:
            tool_choice (str | None): Value supplied to the helper.
            selected_tools (List[Dict[str, Any]] | None): Value supplied to the helper.

        Returns:
            Value produced by the build_text_tool_choice helper according to its function annotation
            and return statements.
    """
	if not isinstance( tool_choice, str ) or not tool_choice.strip( ):
		return None
	choice = tool_choice.strip( )
	if choice not in [ 'auto', 'required', 'none' ]:
		return None
	if choice == 'none':
		return 'none'
	if selected_tools is None or len( selected_tools ) == 0:
		return None
	return choice

build_text_context

build_text_context(
    messages: List[Dict[str, Any]] | None,
    include_last_message: bool = False,
) -> List[Dict[str, str]]

Build text context.

Purpose

Builds the text context value used by the Gipity interface or provider wrapper. The function normalizes inputs and returns a stable object for downstream use.

Parameters:

Name Type Description Default
messages List[Dict[str, Any]] | None

Value supplied to the helper.

required
include_last_message bool

Value supplied to the helper.

False

Returns:

Type Description
List[Dict[str, str]]

Value produced by the build_text_context helper according to its function annotation and

List[Dict[str, str]]

return statements.

Source code in app.py
def build_text_context( messages: List[ Dict[ str, Any ] ] | None,
		include_last_message: bool = False ) -> List[ Dict[ str, str ] ]:
	"""Build text context.

        Purpose:
            Builds the text context value used by the Gipity interface or provider wrapper. The
            function normalizes inputs and returns a stable object for downstream use.

        Args:
            messages (List[Dict[str, Any]] | None): Value supplied to the helper.
            include_last_message (bool): Value supplied to the helper.

        Returns:
            Value produced by the build_text_context helper according to its function annotation and
            return statements.
    """
	if messages is None or not isinstance( messages, list ):
		return [ ]
	items = messages if include_last_message else messages[ :-1 ]
	context: List[ Dict[ str, str ] ] = [ ]
	for item in items:
		if not isinstance( item, dict ):
			continue
		role = str( item.get( 'role', '' ) or '' ).strip( )
		content = item.get( 'content', '' )
		if role not in [ 'user', 'assistant', 'system', 'developer' ]:
			continue
		if not isinstance( content, str ) or not content.strip( ):
			continue
		context.append( { 'role': role, 'content': content.strip( ) } )
	return context

get_text_conversation_id

get_text_conversation_id(
    input_mode: str | None, conversation_id: str | None
) -> str | None

Get text conversation id.

Purpose

Returns the text conversation id value used by the Gipity interface. The helper centralizes option lookup and fallback behavior for callers.

Parameters:

Name Type Description Default
input_mode str | None

Value supplied to the helper.

required
conversation_id str | None

Value supplied to the helper.

required

Returns:

Type Description
str | None

Value produced by the get_text_conversation_id helper according to its function

str | None

annotation and return statements.

Source code in app.py
def get_text_conversation_id( input_mode: str | None, conversation_id: str | None ) -> str | None:
	"""Get text conversation id.

        Purpose:
            Returns the text conversation id value used by the Gipity interface. The helper
            centralizes option lookup and fallback behavior for callers.

        Args:
            input_mode (str | None): Value supplied to the helper.
            conversation_id (str | None): Value supplied to the helper.

        Returns:
            Value produced by the get_text_conversation_id helper according to its function
            annotation and return statements.
    """
	if input_mode != 'conversation':
		return None
	if not isinstance( conversation_id, str ) or not conversation_id.strip( ):
		return None
	return conversation_id.strip( )

get_text_previous_response_id

get_text_previous_response_id(
    input_mode: str | None, previous_id: str | None
) -> str | None

Get text previous response id.

Purpose

Returns the text previous response id value used by the Gipity interface. The helper centralizes option lookup and fallback behavior for callers.

Parameters:

Name Type Description Default
input_mode str | None

Value supplied to the helper.

required
previous_id str | None

Value supplied to the helper.

required

Returns:

Type Description
str | None

Value produced by the get_text_previous_response_id helper according to its function

str | None

annotation and return statements.

Source code in app.py
def get_text_previous_response_id( input_mode: str | None, previous_id: str | None ) -> str | None:
	"""Get text previous response id.

        Purpose:
            Returns the text previous response id value used by the Gipity interface. The helper
            centralizes option lookup and fallback behavior for callers.

        Args:
            input_mode (str | None): Value supplied to the helper.
            previous_id (str | None): Value supplied to the helper.

        Returns:
            Value produced by the get_text_previous_response_id helper according to its function
            annotation and return statements.
    """
	if input_mode == 'single_turn':
		return None
	if input_mode == 'conversation':
		return None
	if not isinstance( previous_id, str ) or not previous_id.strip( ):
		return None
	return previous_id.strip( )

get_text_stream_value

get_text_stream_value(stream_value: bool | None) -> None

Get text stream value.

Purpose

Returns the text stream value value used by the Gipity interface. The helper centralizes option lookup and fallback behavior for callers.

Parameters:

Name Type Description Default
stream_value bool | None

Value supplied to the helper.

required
Source code in app.py
def get_text_stream_value( stream_value: bool | None ) -> None:
	"""Get text stream value.

        Purpose:
            Returns the text stream value value used by the Gipity interface. The helper centralizes
            option lookup and fallback behavior for callers.

        Args:
            stream_value (bool | None): Value supplied to the helper.
    """
	if bool( stream_value ):
		st.info(
			'Streaming is not sent in this Text mode path until stream-event rendering is added.' )
	return None

get_text_background_value

get_text_background_value(
    background_value: bool | None,
) -> None

Get text background value.

Purpose

Returns the text background value value used by the Gipity interface. The helper centralizes option lookup and fallback behavior for callers.

Parameters:

Name Type Description Default
background_value bool | None

Value supplied to the helper.

required
Source code in app.py
def get_text_background_value( background_value: bool | None ) -> None:
	"""Get text background value.

        Purpose:
            Returns the text background value value used by the Gipity interface. The helper
            centralizes option lookup and fallback behavior for callers.

        Args:
            background_value (bool | None): Value supplied to the helper.
    """
	if bool( background_value ):
		st.info( 'Background mode is not sent in this Text mode path until polling is added.' )
	return None

reset_text_structured_output_controls

reset_text_structured_output_controls() -> None

Reset text structured output controls.

Purpose

Resets the text structured output controls state used by the application. The function clears related Streamlit keys without performing provider calls.

Source code in app.py
def reset_text_structured_output_controls( ) -> None:
	"""Reset text structured output controls.

        Purpose:
            Resets the text structured output controls state used by the application. The function
            clears related Streamlit keys without performing provider calls.
    """
	for key in [ 'text_json_schema_name', 'text_json_schema', 'text_json_schema_strict' ]:
		if key in st.session_state:
			del st.session_state[ key ]

reset_text_api_state_controls

reset_text_api_state_controls() -> None

Reset text api state controls.

Purpose

Resets the text api state controls state used by the application. The function clears related Streamlit keys without performing provider calls.

Source code in app.py
def reset_text_api_state_controls( ) -> None:
	"""Reset text api state controls.

        Purpose:
            Resets the text api state controls state used by the application. The function clears
            related Streamlit keys without performing provider calls.
    """
	for key in [ 'text_previous_response_id', 'text_conversation_id' ]:
		if key in st.session_state:
			del st.session_state[ key ]

clear_image_messages

clear_image_messages() -> None

Clear image messages.

Purpose

Clears the image messages state used by the current workflow so the user interface can start from a clean output state.

Source code in app.py
def clear_image_messages( ) -> None:
	"""Clear image messages.

        Purpose:
            Clears the image messages state used by the current workflow so the user interface can
            start from a clean output state.
    """
	st.session_state[ 'image_input' ] = [ ]
	st.session_state[ 'image_messages' ] = [ ]
	st.session_state[ 'image_output_bytes' ] = None

clear_image_instructions

clear_image_instructions() -> None

Clear image instructions.

Purpose

Clears the image instructions state used by the current workflow so the user interface can start from a clean output state.

Source code in app.py
def clear_image_instructions( ) -> None:
	"""Clear image instructions.

        Purpose:
            Clears the image instructions state used by the current workflow so the user interface
            can start from a clean output state.
    """
	st.session_state[ 'image_system_instructions' ] = ''
	st.session_state[ 'instructions' ] = ''

append_image_message

append_image_message(role: str, content: str) -> None

Append image message.

Purpose

Provides the append image message helper used by the Gipity Streamlit application. The function supports UI state management, provider coordination, data normalization, or display behavior required by the surrounding workflow.

Parameters:

Name Type Description Default
role str

Value supplied to the helper.

required
content str

Value supplied to the helper.

required
Source code in app.py
def append_image_message( role: str, content: str ) -> None:
	"""Append image message.

        Purpose:
            Provides the append image message helper used by the Gipity Streamlit application. The
            function supports UI state management, provider coordination, data normalization, or
            display behavior required by the surrounding workflow.

        Args:
            role (str): Value supplied to the helper.
            content (str): Value supplied to the helper.
    """
	if 'image_input' not in st.session_state or not isinstance( st.session_state[ 'image_input' ],
			list ):
		st.session_state[ 'image_input' ] = [ ]
	if 'image_messages' not in st.session_state or not isinstance(
			st.session_state[ 'image_messages' ], list ):
		st.session_state[ 'image_messages' ] = [ ]
	message = { 'role': role, 'content': content }
	st.session_state[ 'image_input' ].append( message )
	st.session_state[ 'image_messages' ].append( message )

load_image_instruction_template

load_image_instruction_template() -> None

Load image instruction template.

Purpose

Loads the image instruction template resource or state required by the Gipity workflow and returns the prepared value for caller use.

Source code in app.py
def load_image_instruction_template( ) -> None:
	"""Load image instruction template.

        Purpose:
            Loads the image instruction template resource or state required by the Gipity workflow
            and returns the prepared value for caller use.
    """
	name = st.session_state.get( 'instructions' )
	if name and name != 'No Templates Found':
		text = fetch_prompt_text( cfg.DB_PATH, name )
		if text is not None:
			st.session_state[ 'image_system_instructions' ] = text

convert_image_system_instructions

convert_image_system_instructions() -> None

Convert image system instructions.

Purpose

Provides the convert image system instructions helper used by the Gipity Streamlit application. The function supports UI state management, provider coordination, data normalization, or display behavior required by the surrounding workflow.

Source code in app.py
def convert_image_system_instructions( ) -> None:
	"""Convert image system instructions.

        Purpose:
            Provides the convert image system instructions helper used by the Gipity Streamlit
            application. The function supports UI state management, provider coordination, data
            normalization, or display behavior required by the surrounding workflow.
    """
	text = st.session_state.get( 'image_system_instructions', '' )
	if not isinstance( text, str ) or not text.strip( ):
		return
	source = text.strip( )
	if cfg.XML_BLOCK_PATTERN.search( source ):
		converted = convert_xml( source )
	else:
		converted = convert_markdown( source )
	st.session_state[ 'image_system_instructions' ] = converted

reset_image_llm_settings

reset_image_llm_settings() -> None

Reset image llm settings.

Purpose

Resets the image llm settings state used by the application. The function clears related Streamlit keys without performing provider calls.

Source code in app.py
def reset_image_llm_settings( ) -> None:
	"""Reset image llm settings.

        Purpose:
            Resets the image llm settings state used by the application. The function clears related
            Streamlit keys without performing provider calls.
    """
	for key in [ 'image_mode', 'image_model', 'image_analysis_model', 'image_number' ]:
		if key in st.session_state:
			del st.session_state[ key ]

reset_image_visual_settings

reset_image_visual_settings() -> None

Reset image visual settings.

Purpose

Resets the image visual settings state used by the application. The function clears related Streamlit keys without performing provider calls.

Source code in app.py
def reset_image_visual_settings( ) -> None:
	"""Reset image visual settings.

        Purpose:
            Resets the image visual settings state used by the application. The function clears
            related Streamlit keys without performing provider calls.
    """
	for key in [ 'image_mime_type', 'image_size', 'image_quality', 'image_backcolor',
	             'image_compression' ]:
		if key in st.session_state:
			del st.session_state[ key ]

get_image_models

get_image_models(image: Images) -> List[str]

Get image models.

Purpose

Returns the image models value used by the Gipity interface. The helper centralizes option lookup and fallback behavior for callers.

Parameters:

Name Type Description Default
image Images

Value supplied to the helper.

required

Returns:

Type Description
List[str]

Value produced by the get_image_models helper according to its function annotation and

List[str]

return statements.

Source code in app.py
def get_image_models( image: Images ) -> List[ str ]:
	"""Get image models.

        Purpose:
            Returns the image models value used by the Gipity interface. The helper centralizes
            option lookup and fallback behavior for callers.

        Args:
            image (Images): Value supplied to the helper.

        Returns:
            Value produced by the get_image_models helper according to its function annotation and
            return statements.
    """
	options = getattr( image, 'model_options', None )
	if isinstance( options, list ) and len( options ) > 0:
		return [ '' ] + options
	return [ '', 'gpt-image-2', 'gpt-image-1.5', 'gpt-image-1', 'gpt-image-1-mini' ]

get_image_analysis_models

get_image_analysis_models(
    image: Images = None,
) -> List[str]

Get image analysis models.

Purpose

Returns the image analysis models value used by the Gipity interface. The helper centralizes option lookup and fallback behavior for callers.

Parameters:

Name Type Description Default
image Images

Value supplied to the helper.

None

Returns:

Type Description
List[str]

Value produced by the get_image_analysis_models helper according to its function

List[str]

annotation and return statements.

Source code in app.py
def get_image_analysis_models( image: Images = None ) -> List[ str ]:
	"""Get image analysis models.

        Purpose:
            Returns the image analysis models value used by the Gipity interface. The helper
            centralizes option lookup and fallback behavior for callers.

        Args:
            image (Images): Value supplied to the helper.

        Returns:
            Value produced by the get_image_analysis_models helper according to its function
            annotation and return statements.
    """
	if image is not None:
		options = getattr( image, 'analysis_model_options', None )
		if isinstance( options, list ) and len( options ) > 0:
			return [ '' ] + options
	return [ '', 'gpt-4o-mini', 'gpt-4o', 'gpt-4.1-mini', 'gpt-4.1', 'gpt-5-mini', 'gpt-5' ]

get_image_size_options

get_image_size_options(image: Images) -> List[str]

Get image size options.

Purpose

Returns the image size options value used by the Gipity interface. The helper centralizes option lookup and fallback behavior for callers.

Parameters:

Name Type Description Default
image Images

Value supplied to the helper.

required

Returns:

Type Description
List[str]

Value produced by the get_image_size_options helper according to its function annotation

List[str]

and return statements.

Source code in app.py
def get_image_size_options( image: Images ) -> List[ str ]:
	"""Get image size options.

        Purpose:
            Returns the image size options value used by the Gipity interface. The helper
            centralizes option lookup and fallback behavior for callers.

        Args:
            image (Images): Value supplied to the helper.

        Returns:
            Value produced by the get_image_size_options helper according to its function annotation
            and return statements.
    """
	options = getattr( image, 'size_options', None )
	if isinstance( options, list ) and len( options ) > 0:
		return [ '' ] + options
	return [ '', 'auto', '1024x1024', '1024x1536', '1536x1024' ]

get_image_quality_options

get_image_quality_options(image: Images) -> List[str]

Get image quality options.

Purpose

Returns the image quality options value used by the Gipity interface. The helper centralizes option lookup and fallback behavior for callers.

Parameters:

Name Type Description Default
image Images

Value supplied to the helper.

required

Returns:

Type Description
List[str]

Value produced by the get_image_quality_options helper according to its function

List[str]

annotation and return statements.

Source code in app.py
def get_image_quality_options( image: Images ) -> List[ str ]:
	"""Get image quality options.

        Purpose:
            Returns the image quality options value used by the Gipity interface. The helper
            centralizes option lookup and fallback behavior for callers.

        Args:
            image (Images): Value supplied to the helper.

        Returns:
            Value produced by the get_image_quality_options helper according to its function
            annotation and return statements.
    """
	options = getattr( image, 'quality_options', None )
	if isinstance( options, list ) and len( options ) > 0:
		return [ '' ] + options
	return [ '', 'auto', 'low', 'medium', 'high' ]

get_image_mime_options

get_image_mime_options(image: Images) -> List[str]

Get image mime options.

Purpose

Returns the image mime options value used by the Gipity interface. The helper centralizes option lookup and fallback behavior for callers.

Parameters:

Name Type Description Default
image Images

Value supplied to the helper.

required

Returns:

Type Description
List[str]

Value produced by the get_image_mime_options helper according to its function annotation

List[str]

and return statements.

Source code in app.py
def get_image_mime_options( image: Images ) -> List[ str ]:
	"""Get image mime options.

        Purpose:
            Returns the image mime options value used by the Gipity interface. The helper
            centralizes option lookup and fallback behavior for callers.

        Args:
            image (Images): Value supplied to the helper.

        Returns:
            Value produced by the get_image_mime_options helper according to its function annotation
            and return statements.
    """
	options = getattr( image, 'mime_options', None )
	if isinstance( options, list ) and len( options ) > 0:
		return [ '' ] + options
	return [ '', 'png', 'jpeg', 'webp' ]

get_image_background_options

get_image_background_options(image: Images) -> List[str]

Get image background options.

Purpose

Returns the image background options value used by the Gipity interface. The helper centralizes option lookup and fallback behavior for callers.

Parameters:

Name Type Description Default
image Images

Value supplied to the helper.

required

Returns:

Type Description
List[str]

Value produced by the get_image_background_options helper according to its function

List[str]

annotation and return statements.

Source code in app.py
def get_image_background_options( image: Images ) -> List[ str ]:
	"""Get image background options.

        Purpose:
            Returns the image background options value used by the Gipity interface. The helper
            centralizes option lookup and fallback behavior for callers.

        Args:
            image (Images): Value supplied to the helper.

        Returns:
            Value produced by the get_image_background_options helper according to its function
            annotation and return statements.
    """
	options = getattr( image, 'backcolor_options', None )
	if isinstance( options, list ) and len( options ) > 0:
		return [ '' ] + options
	return [ '', 'auto', 'transparent', 'opaque' ]

get_image_detail_options

get_image_detail_options(image: Images) -> List[str]

Get image detail options.

Purpose

Returns the image detail options value used by the Gipity interface. The helper centralizes option lookup and fallback behavior for callers.

Parameters:

Name Type Description Default
image Images

Value supplied to the helper.

required

Returns:

Type Description
List[str]

Value produced by the get_image_detail_options helper according to its function

List[str]

annotation and return statements.

Source code in app.py
def get_image_detail_options( image: Images ) -> List[ str ]:
	"""Get image detail options.

        Purpose:
            Returns the image detail options value used by the Gipity interface. The helper
            centralizes option lookup and fallback behavior for callers.

        Args:
            image (Images): Value supplied to the helper.

        Returns:
            Value produced by the get_image_detail_options helper according to its function
            annotation and return statements.
    """
	options = getattr( image, 'detail_options', None )
	if isinstance( options, list ) and len( options ) > 0:
		return [ '' ] + options
	return [ '', 'auto', 'low', 'high', 'original' ]

render_image_output

render_image_output(
    image_result: str | bytes | List[str | bytes] | None,
    caption: str = "Image output",
) -> bool

Render image output.

Purpose

Renders the image output user-interface section or display element in Streamlit while preserving the application state expected by the surrounding workflow.

Parameters:

Name Type Description Default
image_result str | bytes | List[str | bytes] | None

Value supplied to the helper.

required
caption str

Value supplied to the helper.

'Image output'

Returns:

Type Description
bool

Value produced by the render_image_output helper according to its function annotation

bool

and return statements.

Source code in app.py
def render_image_output( image_result: str | bytes | List[ str | bytes ] | None,
		caption: str='Image output' ) -> bool:
	"""Render image output.

        Purpose:
            Renders the image output user-interface section or display element in Streamlit while
            preserving the application state expected by the surrounding workflow.

        Args:
            image_result (str | bytes | List[str | bytes] | None): Value supplied to the helper.
            caption (str): Value supplied to the helper.

        Returns:
            Value produced by the render_image_output helper according to its function annotation
            and return statements.
    """
	if image_result is None:
		return False
	outputs: List[ str | bytes ] = image_result if isinstance( image_result, list ) else [
			image_result ]
	rendered = False
	for index, item in enumerate( outputs, start=1 ):
		if item is None:
			continue
		if isinstance( item, bytes ) and len( item ) > 0:
			if len( outputs ) > 1:
				st.image( item, caption=f'{caption} {index}', use_column_width=True )
			else:
				st.image( item, caption=caption, use_column_width=True )
			rendered = True
			continue
		if isinstance( item, str ) and item.strip( ):
			if item.strip( ).lower( ).startswith( ('http://', 'https://') ):
				if len( outputs ) > 1:
					st.image( item.strip( ), caption=f'{caption} {index}', use_column_width=True )
				else:
					st.image( item.strip( ), caption=caption, use_column_width=True )
				rendered = True
			else:
				st.markdown( item.strip( ) )
				rendered = True
	return rendered

ensure_embeddings_mode_state

ensure_embeddings_mode_state() -> None

Ensure embeddings mode state.

Purpose

Ensures the required embeddings mode state session-state keys or runtime resources exist before the related interface controls are rendered.

Source code in app.py
def ensure_embeddings_mode_state( ) -> None:
	"""Ensure embeddings mode state.

        Purpose:
            Ensures the required embeddings mode state session-state keys or runtime resources exist
            before the related interface controls are rendered.
    """
	if 'embedding_model' not in st.session_state:
		st.session_state[ 'embedding_model' ] = ''
	if 'embeddings_dimensions' not in st.session_state:
		st.session_state[ 'embeddings_dimensions' ] = 0
	if 'embeddings_chunk_size' not in st.session_state:
		st.session_state[ 'embeddings_chunk_size' ] = 800
	if 'embeddings_overlap_amount' not in st.session_state:
		st.session_state[ 'embeddings_overlap_amount' ] = 0
	if 'embeddings_input_text' not in st.session_state:
		st.session_state[ 'embeddings_input_text' ] = ''
	if 'embeddings_encoding_format' not in st.session_state:
		st.session_state[ 'embeddings_encoding_format' ] = 'float'
	if 'embeddings_user' not in st.session_state:
		st.session_state[ 'embeddings_user' ] = ''
	if 'embeddings' not in st.session_state:
		st.session_state[ 'embeddings' ] = [ ]
	if 'embeddings_chunks' not in st.session_state:
		st.session_state[ 'embeddings_chunks' ] = [ ]
	if 'embeddings_df' not in st.session_state:
		st.session_state[ 'embeddings_df' ] = pd.DataFrame( )
	if 'embedding_metrics' not in st.session_state:
		st.session_state[ 'embedding_metrics' ] = { }
	if 'embedding_usage' not in st.session_state:
		st.session_state[ 'embedding_usage' ] = { }

get_embedding_model_options

get_embedding_model_options(
    embedding: Embeddings,
) -> List[str]

Get embedding model options.

Purpose

Returns the embedding model options value used by the Gipity interface. The helper centralizes option lookup and fallback behavior for callers.

Parameters:

Name Type Description Default
embedding Embeddings

Value supplied to the helper.

required

Returns:

Type Description
List[str]

Value produced by the get_embedding_model_options helper according to its function

List[str]

annotation and return statements.

Source code in app.py
def get_embedding_model_options( embedding: Embeddings ) -> List[ str ]:
	"""Get embedding model options.

        Purpose:
            Returns the embedding model options value used by the Gipity interface. The helper
            centralizes option lookup and fallback behavior for callers.

        Args:
            embedding (Embeddings): Value supplied to the helper.

        Returns:
            Value produced by the get_embedding_model_options helper according to its function
            annotation and return statements.
    """
	options = getattr( embedding, 'model_options', None )
	if isinstance( options, list ) and len( options ) > 0:
		return [ '' ] + options
	return [ '', 'text-embedding-3-small', 'text-embedding-3-large', 'text-embedding-ada-002' ]

get_embedding_encoding_options

get_embedding_encoding_options(
    embedding: Embeddings,
) -> List[str]

Get embedding encoding options.

Purpose

Returns the embedding encoding options value used by the Gipity interface. The helper centralizes option lookup and fallback behavior for callers.

Parameters:

Name Type Description Default
embedding Embeddings

Value supplied to the helper.

required

Returns:

Type Description
List[str]

Value produced by the get_embedding_encoding_options helper according to its function

List[str]

annotation and return statements.

Source code in app.py
def get_embedding_encoding_options( embedding: Embeddings ) -> List[ str ]:
	"""Get embedding encoding options.

        Purpose:
            Returns the embedding encoding options value used by the Gipity interface. The helper
            centralizes option lookup and fallback behavior for callers.

        Args:
            embedding (Embeddings): Value supplied to the helper.

        Returns:
            Value produced by the get_embedding_encoding_options helper according to its function
            annotation and return statements.
    """
	options = getattr( embedding, 'encoding_options', None )
	if isinstance( options, list ) and len( options ) > 0:
		return options
	return [ 'float', 'base64' ]

get_embedding_max_dimensions

get_embedding_max_dimensions(
    model: str | None, embedding: Embeddings
) -> int

Get embedding max dimensions.

Purpose

Returns the embedding max dimensions value used by the Gipity interface. The helper centralizes option lookup and fallback behavior for callers.

Parameters:

Name Type Description Default
model str | None

Value supplied to the helper.

required
embedding Embeddings

Value supplied to the helper.

required

Returns:

Type Description
int

Value produced by the get_embedding_max_dimensions helper according to its function

int

annotation and return statements.

Source code in app.py
def get_embedding_max_dimensions( model: str | None, embedding: Embeddings ) -> int:
	"""Get embedding max dimensions.

        Purpose:
            Returns the embedding max dimensions value used by the Gipity interface. The helper
            centralizes option lookup and fallback behavior for callers.

        Args:
            model (str | None): Value supplied to the helper.
            embedding (Embeddings): Value supplied to the helper.

        Returns:
            Value produced by the get_embedding_max_dimensions helper according to its function
            annotation and return statements.
    """
	if not isinstance( model, str ) or not model.strip( ):
		return 1536
	try:
		return int( embedding.get_max_dimensions( model.strip( ) ) )
	except Exception as e:
		exception = Error( e )
		exception.module = 'app'
		exception.cause = 'get_embedding_max_dimensions'
		exception.method = 'get_embedding_max_dimensions( ... )'
		Logger( ).write( exception )
		if model == 'text-embedding-3-large':
			return 3072
		return 1536

embedding_model_supports_dimensions

embedding_model_supports_dimensions(
    model: str | None, embedding: Embeddings
) -> bool

Embedding model supports dimensions.

Purpose

Provides the embedding model supports dimensions helper used by the Gipity Streamlit application. The function supports UI state management, provider coordination, data normalization, or display behavior required by the surrounding workflow.

Parameters:

Name Type Description Default
model str | None

Value supplied to the helper.

required
embedding Embeddings

Value supplied to the helper.

required

Returns:

Type Description
bool

Value produced by the embedding_model_supports_dimensions helper according to its

bool

function annotation and return statements.

Source code in app.py
def embedding_model_supports_dimensions( model: str | None, embedding: Embeddings ) -> bool:
	"""Embedding model supports dimensions.

        Purpose:
            Provides the embedding model supports dimensions helper used by the Gipity Streamlit
            application. The function supports UI state management, provider coordination, data
            normalization, or display behavior required by the surrounding workflow.

        Args:
            model (str | None): Value supplied to the helper.
            embedding (Embeddings): Value supplied to the helper.

        Returns:
            Value produced by the embedding_model_supports_dimensions helper according to its
            function annotation and return statements.
    """
	if not isinstance( model, str ) or not model.strip( ):
		return False
	support = getattr( embedding, 'model_dimension_support', { } )
	if isinstance( support, dict ):
		return bool( support.get( model.strip( ), False ) )
	return model.strip( ) in [ 'text-embedding-3-small', 'text-embedding-3-large' ]

normalize_embedding_dimensions

normalize_embedding_dimensions(
    model: str | None,
    dimensions: int | None,
    embedding: Embeddings,
) -> int | None

Normalize embedding dimensions.

Purpose

Normalizes the embedding dimensions input into the stable shape expected by downstream Gipity helpers and display logic.

Parameters:

Name Type Description Default
model str | None

Value supplied to the helper.

required
dimensions int | None

Value supplied to the helper.

required
embedding Embeddings

Value supplied to the helper.

required

Returns:

Type Description
int | None

Value produced by the normalize_embedding_dimensions helper according to its function

int | None

annotation and return statements.

Source code in app.py
def normalize_embedding_dimensions( model: str | None, dimensions: int | None,
		embedding: Embeddings ) -> int | None:
	"""Normalize embedding dimensions.

        Purpose:
            Normalizes the embedding dimensions input into the stable shape expected by downstream
            Gipity helpers and display logic.

        Args:
            model (str | None): Value supplied to the helper.
            dimensions (int | None): Value supplied to the helper.
            embedding (Embeddings): Value supplied to the helper.

        Returns:
            Value produced by the normalize_embedding_dimensions helper according to its function
            annotation and return statements.
    """
	if not isinstance( model, str ) or not model.strip( ):
		return None
	if dimensions is None:
		return None
	try:
		value = int( dimensions )
	except Exception as e:
		exception = Error( e )
		exception.module = 'app'
		exception.cause = 'normalize_embedding_dimensions'
		exception.method = 'normalize_embedding_dimensions( ... )'
		Logger( ).write( exception )
		return None
	if value <= 0:
		return None
	if not embedding_model_supports_dimensions( model, embedding ):
		return None
	max_dimensions = get_embedding_max_dimensions( model, embedding )
	if value > max_dimensions:
		return max_dimensions
	return value

normalize_embedding_chunk_settings

normalize_embedding_chunk_settings(
    chunk_size: int | None, overlap_amount: int | None
) -> tuple[int, int]

Normalize embedding chunk settings.

Purpose

Normalizes the embedding chunk settings input into the stable shape expected by downstream Gipity helpers and display logic.

Parameters:

Name Type Description Default
chunk_size int | None

Value supplied to the helper.

required
overlap_amount int | None

Value supplied to the helper.

required

Returns:

Type Description
int

Value produced by the normalize_embedding_chunk_settings helper according to its

int

function annotation and return statements.

Source code in app.py
def normalize_embedding_chunk_settings( chunk_size: int | None,
	overlap_amount: int | None ) ->  tuple[ int, int ]:
	"""Normalize embedding chunk settings.

        Purpose:
            Normalizes the embedding chunk settings input into the stable shape expected by
            downstream Gipity helpers and display logic.

        Args:
            chunk_size (int | None): Value supplied to the helper.
            overlap_amount (int | None): Value supplied to the helper.

        Returns:
            Value produced by the normalize_embedding_chunk_settings helper according to its
            function annotation and return statements.
    """
	try:
		chunk_value = int( chunk_size )
	except Exception as e:
		exception = Error( e )
		exception.module = 'app'
		exception.cause = 'normalize_embedding_chunk_settings'
		exception.method = 'normalize_embedding_chunk_settings( ... )'
		Logger( ).write( exception )
		chunk_value = 800
	try:
		overlap_value = int( overlap_amount )
	except Exception as e:
		exception = Error( e )
		exception.module = 'app'
		exception.cause = 'normalize_embedding_chunk_settings'
		exception.method = 'normalize_embedding_chunk_settings( ... )'
		Logger( ).write( exception )
		overlap_value = 0
	if chunk_value <= 0:
		chunk_value = 800
	if chunk_value > 8192:
		chunk_value = 8192
	if overlap_value < 0:
		overlap_value = 0
	if overlap_value >= chunk_value:
		overlap_value = max( 0, chunk_value // 5 )
	return (chunk_value, overlap_value)

chunk_text_for_embeddings

chunk_text_for_embeddings(
    text: str,
    chunk_size: int = 800,
    overlap_amount: int = 0,
    encoding_name: str = "cl100k_base",
) -> List[str]

Chunk text for embeddings.

Purpose

Provides the chunk text for embeddings helper used by the Gipity Streamlit application. The function supports UI state management, provider coordination, data normalization, or display behavior required by the surrounding workflow.

Parameters:

Name Type Description Default
text str

Value supplied to the helper.

required
chunk_size int

Value supplied to the helper.

800
overlap_amount int

Value supplied to the helper.

0
encoding_name str

Value supplied to the helper.

'cl100k_base'

Returns:

Type Description
List[str]

Value produced by the chunk_text_for_embeddings helper according to its function

List[str]

annotation and return statements.

Source code in app.py
def chunk_text_for_embeddings( text: str, chunk_size: int = 800, overlap_amount: int = 0,
		encoding_name: str = 'cl100k_base' ) -> List[ str ]:
	"""Chunk text for embeddings.

        Purpose:
            Provides the chunk text for embeddings helper used by the Gipity Streamlit application.
            The function supports UI state management, provider coordination, data normalization, or
            display behavior required by the surrounding workflow.

        Args:
            text (str): Value supplied to the helper.
            chunk_size (int): Value supplied to the helper.
            overlap_amount (int): Value supplied to the helper.
            encoding_name (str): Value supplied to the helper.

        Returns:
            Value produced by the chunk_text_for_embeddings helper according to its function
            annotation and return statements.
    """
	if not isinstance( text, str ) or not text.strip( ):
		return [ ]
	chunk_value, overlap_value = normalize_embedding_chunk_settings( chunk_size=chunk_size,
		overlap_amount=overlap_amount )
	encoding = tiktoken.get_encoding( encoding_name )
	tokens = encoding.encode( text )
	if len( tokens ) == 0:
		return [ ]
	chunks: List[ str ] = [ ]
	start = 0
	step = max( 1, chunk_value - overlap_value )
	while start < len( tokens ):
		end = min( start + chunk_value, len( tokens ) )
		chunk_tokens = tokens[ start:end ]
		chunk_text_value = encoding.decode( chunk_tokens ).strip( )
		if chunk_text_value:
			chunks.append( chunk_text_value )
		if end >= len( tokens ):
			break
		start += step
	return chunks

normalize_embedding_vectors

normalize_embedding_vectors(vectors: Any) -> List[Any]

Normalize embedding vectors.

Purpose

Normalizes the embedding vectors input into the stable shape expected by downstream Gipity helpers and display logic.

Parameters:

Name Type Description Default
vectors Any

Value supplied to the helper.

required

Returns:

Type Description
List[Any]

Value produced by the normalize_embedding_vectors helper according to its function

List[Any]

annotation and return statements.

Source code in app.py
def normalize_embedding_vectors( vectors: Any ) -> List[ Any ]:
	"""Normalize embedding vectors.

        Purpose:
            Normalizes the embedding vectors input into the stable shape expected by downstream
            Gipity helpers and display logic.

        Args:
            vectors (Any): Value supplied to the helper.

        Returns:
            Value produced by the normalize_embedding_vectors helper according to its function
            annotation and return statements.
    """
	if vectors is None:
		return [ ]
	if isinstance( vectors, str ):
		return [ vectors ]
	if isinstance( vectors, list ):
		if len( vectors ) == 0:
			return [ ]
		if all( (isinstance( value, (int, float) ) for value in vectors) ):
			return [ vectors ]
		return vectors
	return [ vectors ]

build_embeddings_dataframe

build_embeddings_dataframe(
    chunks: List[str],
    vectors: Any,
    encoding_format: str = "float",
) -> pd.DataFrame

Build embeddings dataframe.

Purpose

Builds the embeddings dataframe value used by the Gipity interface or provider wrapper. The function normalizes inputs and returns a stable object for downstream use.

Parameters:

Name Type Description Default
chunks List[str]

Value supplied to the helper.

required
vectors Any

Value supplied to the helper.

required
encoding_format str

Value supplied to the helper.

'float'

Returns:

Type Description
DataFrame

Value produced by the build_embeddings_dataframe helper according to its function

DataFrame

annotation and return statements.

Source code in app.py
def build_embeddings_dataframe( chunks: List[ str ], vectors: Any,
		encoding_format: str = 'float' ) -> pd.DataFrame:
	"""Build embeddings dataframe.

        Purpose:
            Builds the embeddings dataframe value used by the Gipity interface or provider wrapper.
            The function normalizes inputs and returns a stable object for downstream use.

        Args:
            chunks (List[str]): Value supplied to the helper.
            vectors (Any): Value supplied to the helper.
            encoding_format (str): Value supplied to the helper.

        Returns:
            Value produced by the build_embeddings_dataframe helper according to its function
            annotation and return statements.
    """
	outputs = normalize_embedding_vectors( vectors )
	if len( outputs ) == 0:
		return pd.DataFrame( )
	rows: List[ Dict[ str, Any ] ] = [ ]
	format_value = encoding_format if isinstance( encoding_format, str ) else 'float'
	if format_value == 'base64':
		for index, item in enumerate( outputs ):
			chunk = chunks[ index ] if index < len( chunks ) else ''
			rows.append( { 'ChunkIndex': index + 1, 'Chunk': chunk,
			               'EmbeddingBase64': item if isinstance( item, str ) else str( item ) } )
		return pd.DataFrame( rows )
	for index, vector in enumerate( outputs ):
		chunk = chunks[ index ] if index < len( chunks ) else ''
		if not isinstance( vector, list ):
			rows.append( { 'ChunkIndex': index + 1, 'Chunk': chunk, 'Embedding': str( vector ) } )
			continue
		row: Dict[ str, Any ] = { 'ChunkIndex': index + 1, 'Chunk': chunk }
		for dim_index, value in enumerate( vector ):
			row[ f'dim_{dim_index}' ] = value
		rows.append( row )
	return pd.DataFrame( rows )

get_embedding_vector_dimension

get_embedding_vector_dimension(vectors: Any) -> int

Get embedding vector dimension.

Purpose

Returns the embedding vector dimension value used by the Gipity interface. The helper centralizes option lookup and fallback behavior for callers.

Parameters:

Name Type Description Default
vectors Any

Value supplied to the helper.

required

Returns:

Type Description
int

Value produced by the get_embedding_vector_dimension helper according to its function

int

annotation and return statements.

Source code in app.py
def get_embedding_vector_dimension( vectors: Any ) -> int:
	"""Get embedding vector dimension.

        Purpose:
            Returns the embedding vector dimension value used by the Gipity interface. The helper
            centralizes option lookup and fallback behavior for callers.

        Args:
            vectors (Any): Value supplied to the helper.

        Returns:
            Value produced by the get_embedding_vector_dimension helper according to its function
            annotation and return statements.
    """
	outputs = normalize_embedding_vectors( vectors )
	if len( outputs ) == 0:
		return 0
	first = outputs[ 0 ]
	if isinstance( first, list ):
		return len( first )
	return 0

extract_embedding_usage

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

Extract embedding usage.

Purpose

Extracts the embedding usage value from the supplied object or payload while handling missing or unsupported content safely.

Parameters:

Name Type Description Default
response Any

Value supplied to the helper.

required

Returns:

Type Description
Dict[str, Any]

Value produced by the extract_embedding_usage helper according to its function

Dict[str, Any]

annotation and return statements.

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

        Purpose:
            Extracts the embedding usage value from the supplied object or payload while handling
            missing or unsupported content safely.

        Args:
            response (Any): Value supplied to the helper.

        Returns:
            Value produced by the extract_embedding_usage helper according to its function
            annotation and return statements.
    """
	if response is None:
		return { }
	try:
		raw = getattr( response, 'usage', None )
	except Exception as e:
		exception = Error( e )
		exception.module = 'app'
		exception.cause = 'extract_embedding_usage'
		exception.method = 'extract_embedding_usage( ... )'
		Logger( ).write( exception )
		raw = None
	if raw is None:
		return { }
	if isinstance( raw, dict ):
		return raw
	if hasattr( raw, 'model_dump' ):
		try:
			return raw.model_dump( )
		except Exception as e:
			exception = Error( e )
			exception.module = 'app'
			exception.cause = 'extract_embedding_usage'
			exception.method = 'extract_embedding_usage( ... )'
			Logger( ).write( exception )
			return { 'raw': str( raw ) }
	return { 'raw': str( raw ) }

build_embedding_metrics

build_embedding_metrics(
    source_text: str,
    normalized_text: str,
    chunks: List[str],
    vectors: Any,
    usage: Dict[str, Any] | None = None,
) -> Dict[str, Any]

Build embedding metrics.

Purpose

Builds the embedding metrics value used by the Gipity interface or provider wrapper. The function normalizes inputs and returns a stable object for downstream use.

Parameters:

Name Type Description Default
source_text str

Value supplied to the helper.

required
normalized_text str

Value supplied to the helper.

required
chunks List[str]

Value supplied to the helper.

required
vectors Any

Value supplied to the helper.

required
usage Dict[str, Any] | None

Value supplied to the helper.

None

Returns:

Type Description
Dict[str, Any]

Value produced by the build_embedding_metrics helper according to its function

Dict[str, Any]

annotation and return statements.

Source code in app.py
def build_embedding_metrics( source_text: str, normalized_text: str, chunks: List[ str ],
		vectors: Any, usage: Dict[ str, Any ] | None = None ) -> Dict[ str, Any ]:
	"""Build embedding metrics.

        Purpose:
            Builds the embedding metrics value used by the Gipity interface or provider wrapper. The
            function normalizes inputs and returns a stable object for downstream use.

        Args:
            source_text (str): Value supplied to the helper.
            normalized_text (str): Value supplied to the helper.
            chunks (List[str]): Value supplied to the helper.
            vectors (Any): Value supplied to the helper.
            usage (Dict[str, Any] | None): Value supplied to the helper.

        Returns:
            Value produced by the build_embedding_metrics helper according to its function
            annotation and return statements.
    """
	source_value = source_text if isinstance( source_text, str ) else ''
	normalized_value = normalized_text if isinstance( normalized_text, str ) else ''
	outputs = normalize_embedding_vectors( vectors )
	words = normalized_value.split( )
	unique_words = set( words )
	token_total = count_tokens( normalized_value ) if normalized_value else 0
	vector_dimension = get_embedding_vector_dimension( outputs )
	metrics: Dict[ str, Any ] = { 'characters': len( source_value ),
	                              'normalized_characters': len( normalized_value ),
	                              'words': len( words ), 'unique_words': len( unique_words ),
	                              'type_token_ratio': round( len( unique_words ) / len( words ),
		                              4 ) if len( words ) else 0.0, 'tokens': token_total,
	                              'chunks': len( chunks ), 'embeddings': len( outputs ),
	                              'vector_dimension': vector_dimension,
	                              'encoding_format': st.session_state.get(
		                              'embeddings_encoding_format', 'float' ),
	                              'usage': usage if isinstance( usage, dict ) else { } }
	return metrics

render_embedding_metrics

render_embedding_metrics(
    metrics: Dict[str, Any] | None,
) -> None

Render embedding metrics.

Purpose

Renders the embedding metrics user-interface section or display element in Streamlit while preserving the application state expected by the surrounding workflow.

Parameters:

Name Type Description Default
metrics Dict[str, Any] | None

Value supplied to the helper.

required
Source code in app.py
def render_embedding_metrics( metrics: Dict[ str, Any ] | None ) -> None:
	"""Render embedding metrics.

        Purpose:
            Renders the embedding metrics user-interface section or display element in Streamlit
            while preserving the application state expected by the surrounding workflow.

        Args:
            metrics (Dict[str, Any] | None): Value supplied to the helper.
    """
	if not isinstance( metrics, dict ) or len( metrics ) == 0:
		return
	metric_c1, metric_c2, metric_c3, metric_c4, metric_c5 = st.columns( [ 0.2, 0.2, 0.2, 0.2, 0.2 ],
		border=True, gap='xxsmall' )
	with metric_c1:
		st.metric( 'Tokens', metrics.get( 'tokens', 0 ) )
	with metric_c2:
		st.metric( 'Chunks', metrics.get( 'chunks', 0 ) )
	with metric_c3:
		st.metric( 'Embeddings', metrics.get( 'embeddings', 0 ) )
	with metric_c4:
		st.metric( 'Dimensions', metrics.get( 'vector_dimension', 0 ) )
	with metric_c5:
		st.metric( 'Words', metrics.get( 'words', 0 ) )

render_embeddings_dataframe

render_embeddings_dataframe(
    df_embeddings: DataFrame,
) -> None

Render embeddings dataframe.

Purpose

Renders the embeddings dataframe user-interface section or display element in Streamlit while preserving the application state expected by the surrounding workflow.

Parameters:

Name Type Description Default
df_embeddings DataFrame

Value supplied to the helper.

required
Source code in app.py
def render_embeddings_dataframe( df_embeddings: pd.DataFrame ) -> None:
	"""Render embeddings dataframe.

        Purpose:
            Renders the embeddings dataframe user-interface section or display element in Streamlit
            while preserving the application state expected by the surrounding workflow.

        Args:
            df_embeddings (pd.DataFrame): Value supplied to the helper.
    """
	if df_embeddings is None or df_embeddings.empty:
		st.info( 'No embeddings available.' )
		return
	st.data_editor( df_embeddings, use_container_width=True, hide_index=True )

reset_embeddings_controls

reset_embeddings_controls() -> None

Reset embeddings controls.

Purpose

Resets the embeddings controls state used by the application. The function clears related Streamlit keys without performing provider calls.

Source code in app.py
def reset_embeddings_controls( ) -> None:
	"""Reset embeddings controls.

        Purpose:
            Resets the embeddings controls state used by the application. The function clears
            related Streamlit keys without performing provider calls.
    """
	for key in [ 'embedding_model', 'embeddings_dimensions', 'embeddings_chunk_size',
	             'embeddings_overlap_amount', 'embeddings_encoding_format', 'embeddings_user' ]:
		if key in st.session_state:
			del st.session_state[ key ]

clear_embeddings_output

clear_embeddings_output() -> None

Clear embeddings output.

Purpose

Clears the embeddings output state used by the current workflow so the user interface can start from a clean output state.

Source code in app.py
def clear_embeddings_output( ) -> None:
	"""Clear embeddings output.

        Purpose:
            Clears the embeddings output state used by the current workflow so the user interface
            can start from a clean output state.
    """
	st.session_state[ 'embeddings' ] = [ ]
	st.session_state[ 'embeddings_chunks' ] = [ ]
	st.session_state[ 'embeddings_df' ] = pd.DataFrame( )
	st.session_state[ 'embedding_metrics' ] = { }
	st.session_state[ 'embedding_usage' ] = { }

reset_embeddings_all

reset_embeddings_all() -> None

Reset embeddings all.

Purpose

Resets the embeddings all state used by the application. The function clears related Streamlit keys without performing provider calls.

Source code in app.py
def reset_embeddings_all( ) -> None:
	"""Reset embeddings all.

        Purpose:
            Resets the embeddings all state used by the application. The function clears related
            Streamlit keys without performing provider calls.
    """
	reset_embeddings_controls( )
	clear_embeddings_output( )
	if 'embeddings_input_text' in st.session_state:
		del st.session_state[ 'embeddings_input_text' ]

load_sqlite_vec

load_sqlite_vec(conn: Connection) -> bool

Load sqlite vec.

Purpose

Loads the sqlite vec resource or state required by the Gipity workflow and returns the prepared value for caller use.

Parameters:

Name Type Description Default
conn Connection

Value supplied to the helper.

required

Returns:

Type Description
bool

Value produced by the load_sqlite_vec helper according to its function annotation and

bool

return statements.

Source code in app.py
def load_sqlite_vec( conn: sqlite3.Connection ) -> bool:
	"""Load sqlite vec.

        Purpose:
            Loads the sqlite vec resource or state required by the Gipity workflow and returns the
            prepared value for caller use.

        Args:
            conn (sqlite3.Connection): Value supplied to the helper.

        Returns:
            Value produced by the load_sqlite_vec helper according to its function annotation and
            return statements.
    """
	try:
		import sqlite_vec

		sqlite_vec.load( conn )
		return True
	except Exception as e:
		exception = Error( e )
		exception.module = 'app'
		exception.cause = 'load_sqlite_vec'
		exception.method = 'load_sqlite_vec( ... )'
		Logger( ).write( exception )
		return False

ensure_vec_schema

ensure_vec_schema(dim: int) -> bool

Ensure vec schema.

Purpose

Ensures the required vec schema session-state keys or runtime resources exist before the related interface controls are rendered.

Parameters:

Name Type Description Default
dim int

Value supplied to the helper.

required

Returns:

Type Description
bool

Value produced by the ensure_vec_schema helper according to its function annotation and

bool

return statements.

Source code in app.py
def ensure_vec_schema( dim: int ) -> bool:
	"""Ensure vec schema.

        Purpose:
            Ensures the required vec schema session-state keys or runtime resources exist before the
            related interface controls are rendered.

        Args:
            dim (int): Value supplied to the helper.

        Returns:
            Value produced by the ensure_vec_schema helper according to its function annotation and
            return statements.
    """
	conn = create_connection( )
	try:
		ok = load_sqlite_vec( conn )
		if not ok:
			return False
		cur = conn.cursor( )
		cur.execute(
			f'\n\t\t\tCREATE VIRTUAL TABLE IF NOT EXISTS docqna_vec\n\t\t\tUSING vec0(\n\t\t\t\tembedding float[{int( dim )}],\n\t\t\t\tdoc_name TEXT,\n\t\t\t\tchunk TEXT\n\t\t\t);\n\t\t\t' )
		conn.commit( )
		return True
	except Exception as e:
		exception = Error( e )
		exception.module = 'app'
		exception.cause = 'ensure_vec_schema'
		exception.method = 'ensure_vec_schema( ... )'
		Logger( ).write( exception )
		return False
	finally:
		conn.close( )

rebuild_index

rebuild_index(embedder: SentenceTransformer) -> None

Rebuild index.

Purpose

Provides the rebuild index helper used by the Gipity Streamlit application. The function supports UI state management, provider coordination, data normalization, or display behavior required by the surrounding workflow.

Parameters:

Name Type Description Default
embedder SentenceTransformer

Value supplied to the helper.

required
Source code in app.py
def rebuild_index( embedder: SentenceTransformer ) -> None:
	"""Rebuild index.

        Purpose:
            Provides the rebuild index helper used by the Gipity Streamlit application. The function
            supports UI state management, provider coordination, data normalization, or display
            behavior required by the surrounding workflow.

        Args:
            embedder (SentenceTransformer): Value supplied to the helper.
    """
	active_docs: List[ str ] = st.session_state.get( 'docqna_active_docs', [ ] )
	doc_bytes: Dict[ str, bytes ] = st.session_state.get( 'docqna_bytes', { } )
	fp = compute_fingerprint( active_docs, doc_bytes )
	if fp and fp == st.session_state.get( 'docqna_fingerprint', '' ):
		return
	st.session_state[ 'docqna_fingerprint' ] = fp
	st.session_state[ 'docqna_chunk_count' ] = 0
	st.session_state[ 'docqna_fallback_rows' ] = [ ]
	dim_value = getattr( embedder, 'get_sentence_embedding_dimension', lambda: 384 )( )
	dim = int( dim_value ) if dim_value else 384
	vec_ready = ensure_vec_schema( dim )
	st.session_state[ 'docqna_vec_ready' ] = bool( vec_ready )
	conn = create_connection( )
	try:
		cur = conn.cursor( )
		if vec_ready:
			try:
				cur.execute( 'DELETE FROM docqna_vec;' )
				conn.commit( )
			except Exception as e:
				exception = Error( e )
				exception.module = 'app'
				exception.cause = 'rebuild_index'
				exception.method = 'rebuild_index( ... )'
				Logger( ).write( exception )
				st.session_state[ 'docqna_vec_ready' ] = False
				vec_ready = False
		total_chunks = 0
		fallback_rows: List[ Tuple[ str, str, bytes ] ] = [ ]
		for name in active_docs:
			b = doc_bytes.get( name )
			if not b:
				continue
			text = extract_text_from_bytes( b )
			if not text:
				continue
			chunks = chunk_text( text )
			if not chunks:
				continue
			vecs = embedder.encode( chunks, show_progress_bar=False )
			vecs = np.asarray( vecs, dtype=np.float32 )
			if vec_ready:
				for chunk_text_value, v in zip( chunks, vecs ):
					cur.execute(
						'INSERT INTO docqna_vec ( embedding, doc_name, chunk ) VALUES ( ?, ?, ? );',
						(v.tobytes( ), name, chunk_text_value) )
			else:
				for chunk_text_value, v in zip( chunks, vecs ):
					fallback_rows.append( (name, chunk_text_value, v.tobytes( )) )
			total_chunks += int( len( chunks ) )
		conn.commit( )
		st.session_state[ 'docqna_chunk_count' ] = total_chunks
		if not vec_ready:
			st.session_state[ 'docqna_fallback_rows' ] = fallback_rows
	except Exception as e:
		exception = Error( e )
		exception.module = 'app'
		exception.cause = 'rebuild_index'
		exception.method = 'rebuild_index( ... )'
		Logger( ).write( exception )
		st.session_state[ 'docqna_vec_ready' ] = False
		st.session_state[ 'docqna_fallback_rows' ] = [ ]
		st.session_state[ 'docqna_chunk_count' ] = 0
	finally:
		conn.close( )

retrieve_top_doc_chunks

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

Retrieve top doc chunks.

Purpose

Provides the retrieve top doc chunks helper used by the Gipity Streamlit application. The function supports UI state management, provider coordination, data normalization, or display behavior required by the surrounding workflow.

Parameters:

Name Type Description Default
query str

Value supplied to the helper.

required
k int

Value supplied to the helper.

6

Returns:

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

Value produced by the retrieve_top_doc_chunks helper according to its function

List[Tuple[str, str, float]]

annotation and return statements.

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:
            Provides the retrieve top doc chunks helper used by the Gipity Streamlit application.
            The function supports UI state management, provider coordination, data normalization, or
            display behavior required by the surrounding workflow.

        Args:
            query (str): Value supplied to the helper.
            k (int): Value supplied to the helper.

        Returns:
            Value produced by the retrieve_top_doc_chunks helper according to its function
            annotation and return statements.
    """
	if not query or not query.strip( ):
		return [ ]
	embedder: SentenceTransformer = load_embedder( )
	rebuild_index( 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:
			load_sqlite_vec( conn )
			cur = conn.cursor( )
			cur.execute(
				'\n                SELECT doc_name, chunk, distance\n                FROM docqna_vec\n                WHERE embedding MATCH ?\n                ORDER BY distance ASC LIMIT ?;\n\t\t\t\t',
				(qv.tobytes( ), int( k )) )
			rows = cur.fetchall( )
			return [ (r[ 0 ], r[ 1 ], float( r[ 2 ] )) for r in rows ]
		except Exception as e:
			exception = Error( e )
			exception.module = 'app'
			exception.cause = 'retrieve_top_doc_chunks'
			exception.method = 'retrieve_top_doc_chunks( ... )'
			Logger( ).write( 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 document user input value used by the Gipity interface or provider wrapper. The function normalizes inputs and returns a stable object for downstream use.

Parameters:

Name Type Description Default
user_query str

Value supplied to the helper.

required
k int

Value supplied to the helper.

6

Returns:

Type Description
str

Value produced by the build_document_user_input helper according to its function

str

annotation and return statements.

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

        Purpose:
            Builds the document user input value used by the Gipity interface or provider wrapper.
            The function normalizes inputs and returns a stable object for downstream use.

        Args:
            user_query (str): Value supplied to the helper.
            k (int): Value supplied to the helper.

        Returns:
            Value produced by the build_document_user_input helper according to its function
            annotation and return statements.
    """
	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(
			f'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{context}' )
	prompt_parts.append( f'Question:\n{user_query}\n\nAnswer:' )
	return '\n\n'.join( prompt_parts ).strip( )

extract_text_from_bytes

extract_text_from_bytes(file_bytes: bytes) -> str

Extract text from bytes.

Purpose

Extracts text from bytes for downstream application use. The function normalizes provider or file-system data into a stable shape that the Streamlit interface and helper workflows can consume safely.

Parameters:

Name Type Description Default
file_bytes bytes

File bytes value used by this workflow.

required

Returns:

Type Description
str

Value produced by the operation for display or downstream processing.

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

    Purpose:
        Extracts text from bytes for downstream application use. The function normalizes
        provider or file-system data into a stable shape that the Streamlit interface and helper
        workflows can consume safely.

    Args:
        file_bytes (bytes): File bytes value used by this workflow.

    Returns:
        Value produced by the operation for display or downstream processing.
    """
	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 as _logged_exception:
		try:
			error = Error( _logged_exception )
			error.module = 'app'
			error.cause = 'extract_text_from_bytes'
			error.method = 'extract_text_from_bytes( file_bytes: bytes )'
			Logger( ).write( error )
		except Exception:
			pass
		try:
			return file_bytes.decode( errors="ignore" )
		except Exception as _logged_exception:
			try:
				error = Error( _logged_exception )
				error.module = 'app'
				error.cause = 'extract_text_from_bytes'
				error.method = 'extract_text_from_bytes( file_bytes: bytes )'
				Logger( ).write( error )
			except Exception:
				pass
			return ""

extract_docqna_pdf_text

extract_docqna_pdf_text(file_bytes: bytes) -> str

Extract docqna pdf text.

Purpose

Extracts the docqna pdf text value from the supplied object or payload while handling missing or unsupported content safely.

Parameters:

Name Type Description Default
file_bytes bytes

Value supplied to the helper.

required

Returns:

Type Description
str

Value produced by the extract_docqna_pdf_text helper according to its function

str

annotation and return statements.

Source code in app.py
def extract_docqna_pdf_text( file_bytes: bytes ) -> str:
	"""Extract docqna pdf text.

        Purpose:
            Extracts the docqna pdf text value from the supplied object or payload while handling
            missing or unsupported content safely.

        Args:
            file_bytes (bytes): Value supplied to the helper.

        Returns:
            Value produced by the extract_docqna_pdf_text helper according to its function
            annotation and return statements.
    """
	if not isinstance( file_bytes, bytes ) or len( file_bytes ) == 0:
		return ''
	try:
		import fitz
		pages: List[ str ] = [ ]
		with fitz.open( stream=file_bytes, filetype='pdf' ) as doc:
			for page in doc:
				pages.append( page.get_text( 'text' ) )
		return '\n\n'.join( pages ).strip( )
	except Exception as e:
		exception = Error( e )
		exception.module = 'app'
		exception.cause = 'extract_docqna_pdf_text'
		exception.method = 'extract_docqna_pdf_text( ... )'
		Logger( ).write( exception )
		try:
			return extract_text_from_bytes( file_bytes )
		except Exception as e:
			exception = Error( e )
			exception.module = 'app'
			exception.cause = 'extract_docqna_pdf_text'
			exception.method = 'extract_docqna_pdf_text( ... )'
			Logger( ).write( exception )
			return ''

extract_docqna_text_file

extract_docqna_text_file(file_bytes: bytes) -> str

Extract docqna text file.

Purpose

Extracts the docqna text file value from the supplied object or payload while handling missing or unsupported content safely.

Parameters:

Name Type Description Default
file_bytes bytes

Value supplied to the helper.

required

Returns:

Type Description
str

Value produced by the extract_docqna_text_file helper according to its function

str

annotation and return statements.

Source code in app.py
def extract_docqna_text_file( file_bytes: bytes ) -> str:
	"""Extract docqna text file.

        Purpose:
            Extracts the docqna text file value from the supplied object or payload while handling
            missing or unsupported content safely.

        Args:
            file_bytes (bytes): Value supplied to the helper.

        Returns:
            Value produced by the extract_docqna_text_file helper according to its function
            annotation and return statements.
    """
	if not isinstance( file_bytes, bytes ) or len( file_bytes ) == 0:
		return ''
	for encoding in [ 'utf-8', 'utf-8-sig', 'cp1252', 'latin-1' ]:
		try:
			return file_bytes.decode( encoding ).strip( )
		except Exception as e:
			exception = Error( e )
			exception.module = 'app'
			exception.cause = 'extract_docqna_text_file'
			exception.method = 'extract_docqna_text_file( ... )'
			Logger( ).write( exception )
			continue
	return ''

extract_docqna_docx_text

extract_docqna_docx_text(file_bytes: bytes) -> str

Extract docqna docx text.

Purpose

Extracts the docqna docx text value from the supplied object or payload while handling missing or unsupported content safely.

Parameters:

Name Type Description Default
file_bytes bytes

Value supplied to the helper.

required

Returns:

Type Description
str

Value produced by the extract_docqna_docx_text helper according to its function

str

annotation and return statements.

Source code in app.py
def extract_docqna_docx_text( file_bytes: bytes ) -> str:
	"""Extract docqna docx text.

        Purpose:
            Extracts the docqna docx text value from the supplied object or payload while handling
            missing or unsupported content safely.

        Args:
            file_bytes (bytes): Value supplied to the helper.

        Returns:
            Value produced by the extract_docqna_docx_text helper according to its function
            annotation and return statements.
    """
	if not isinstance( file_bytes, bytes ) or len( file_bytes ) == 0:
		return ''
	try:
		with zipfile.ZipFile( io.BytesIO( file_bytes ) ) as archive:
			xml_bytes = archive.read( 'word/document.xml' )
		root = ET.fromstring( xml_bytes )
		namespace = '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}'
		paragraphs: List[ str ] = [ ]
		for paragraph in root.iter( f'{namespace}p' ):
			parts: List[ str ] = [ ]
			for node in paragraph.iter( f'{namespace}t' ):
				if node.text:
					parts.append( node.text )
			text = ''.join( parts ).strip( )
			if text:
				paragraphs.append( text )
		return '\n\n'.join( paragraphs ).strip( )
	except Exception as e:
		exception = Error( e )
		exception.module = 'app'
		exception.cause = 'extract_docqna_docx_text'
		exception.method = 'extract_docqna_docx_text( ... )'
		Logger( ).write( exception )
		return ''

extract_docqna_text

extract_docqna_text(
    filename: str, file_bytes: bytes
) -> str

Extract docqna text.

Purpose

Extracts the docqna text value from the supplied object or payload while handling missing or unsupported content safely.

Parameters:

Name Type Description Default
filename str

Value supplied to the helper.

required
file_bytes bytes

Value supplied to the helper.

required

Returns:

Type Description
str

Value produced by the extract_docqna_text helper according to its function annotation

str

and return statements.

Source code in app.py
def extract_docqna_text( filename: str, file_bytes: bytes ) -> str:
	"""Extract docqna text.

        Purpose:
            Extracts the docqna text value from the supplied object or payload while handling
            missing or unsupported content safely.

        Args:
            filename (str): Value supplied to the helper.
            file_bytes (bytes): Value supplied to the helper.

        Returns:
            Value produced by the extract_docqna_text helper according to its function annotation
            and return statements.
    """
	extension = get_docqna_file_extension( filename )
	if extension == '.pdf':
		return extract_docqna_pdf_text( file_bytes )
	if extension == '.docx':
		return extract_docqna_docx_text( file_bytes )
	if extension in [ '.txt', '.md', '.csv', '.json', '.xml', '.py', '.cs', '.sql', '.yaml', '.yml',
	                  '.html', '.css', '.js', '.ts' ]:
		return extract_docqna_text_file( file_bytes )
	return extract_docqna_text_file( file_bytes )

ensure_docqna_mode_state

ensure_docqna_mode_state() -> None

Ensure docqna mode state.

Purpose

Ensures the required docqna mode state session-state keys or runtime resources exist before the related interface controls are rendered.

Source code in app.py
def ensure_docqna_mode_state( ) -> None:
	"""Ensure docqna mode state.

        Purpose:
            Ensures the required docqna mode state session-state keys or runtime resources exist
            before the related interface controls are rendered.
    """
	if 'docqna_model' not in st.session_state:
		st.session_state[ 'docqna_model' ] = ''
	if 'docqna_source' not in st.session_state:
		st.session_state[ 'docqna_source' ] = 'Local Upload'
	if 'docqna_uploaded' not in st.session_state:
		st.session_state[ 'docqna_uploaded' ] = None
	if 'docqna_files' not in st.session_state:
		st.session_state[ 'docqna_files' ] = [ ]
	if 'docqna_active_docs' not in st.session_state:
		st.session_state[ 'docqna_active_docs' ] = [ ]
	if 'docqna_bytes' not in st.session_state:
		st.session_state[ 'docqna_bytes' ] = None
	if 'docqna_texts' not in st.session_state:
		st.session_state[ 'docqna_texts' ] = { }
	if 'docqna_chunks' not in st.session_state:
		st.session_state[ 'docqna_chunks' ] = [ ]
	if 'docqna_last_hits' not in st.session_state:
		st.session_state[ 'docqna_last_hits' ] = [ ]
	if 'docqna_last_sources' not in st.session_state:
		st.session_state[ 'docqna_last_sources' ] = [ ]
	if 'docqna_last_answer' not in st.session_state:
		st.session_state[ 'docqna_last_answer' ] = ''
	if 'docqna_context' not in st.session_state:
		st.session_state[ 'docqna_context' ] = ''
	if 'docqna_messages' not in st.session_state:
		st.session_state.docqna_messages = [ ]
	if not isinstance( st.session_state.get( 'docqna_messages' ), list ):
		st.session_state.docqna_messages = [ ]
	if 'docqna_system_instructions' not in st.session_state:
		st.session_state[ 'docqna_system_instructions' ] = ''
	if 'docqna_file_id' not in st.session_state:
		st.session_state[ 'docqna_file_id' ] = ''
	if 'docqna_vector_store_id' not in st.session_state:
		st.session_state[ 'docqna_vector_store_id' ] = ''
	if 'docqna_multi_mode' not in st.session_state:
		st.session_state[ 'docqna_multi_mode' ] = False
	if 'docqna_top_k' not in st.session_state:
		st.session_state[ 'docqna_top_k' ] = 6
	if 'docqna_chunk_size' not in st.session_state:
		st.session_state[ 'docqna_chunk_size' ] = 900
	if 'docqna_chunk_overlap' not in st.session_state:
		st.session_state[ 'docqna_chunk_overlap' ] = 150
	if 'docqna_vec_ready' not in st.session_state:
		st.session_state[ 'docqna_vec_ready' ] = False
	if 'docqna_fingerprint' not in st.session_state:
		st.session_state[ 'docqna_fingerprint' ] = ''
	if 'docqna_chunk_count' not in st.session_state:
		st.session_state[ 'docqna_chunk_count' ] = 0
	if 'docqna_index_status' not in st.session_state:
		st.session_state[ 'docqna_index_status' ] = 'Not indexed'
	if 'docqna_backend' not in st.session_state:
		st.session_state[ 'docqna_backend' ] = 'local'
	if 'docqna_show_diagnostics' not in st.session_state:
		st.session_state[ 'docqna_show_diagnostics' ] = True
	if 'last_answer' not in st.session_state:
		st.session_state[ 'last_answer' ] = ''
	if 'last_sources' not in st.session_state:
		st.session_state[ 'last_sources' ] = [ ]

clear_docqna_messages

clear_docqna_messages() -> None

Clear docqna messages.

Purpose

Clears the docqna messages state used by the current workflow so the user interface can start from a clean output state.

Source code in app.py
def clear_docqna_messages( ) -> None:
	"""Clear docqna messages.

        Purpose:
            Clears the docqna messages state used by the current workflow so the user interface can
            start from a clean output state.
    """
	st.session_state.docqna_messages = [ ]

clear_docqna_outputs

clear_docqna_outputs() -> None

Clear docqna outputs.

Purpose

Clears the docqna outputs state used by the current workflow so the user interface can start from a clean output state.

Source code in app.py
def clear_docqna_outputs( ) -> None:
	"""Clear docqna outputs.

        Purpose:
            Clears the docqna outputs state used by the current workflow so the user interface can
            start from a clean output state.
    """
	st.session_state[ 'docqna_last_answer' ] = ''
	st.session_state[ 'docqna_last_hits' ] = [ ]
	st.session_state[ 'docqna_last_sources' ] = [ ]
	st.session_state[ 'docqna_context' ] = ''
	st.session_state[ 'last_answer' ] = ''
	st.session_state[ 'last_sources' ] = [ ]

unload_docqna_documents

unload_docqna_documents() -> None

Unload docqna documents.

Purpose

Provides the unload docqna documents helper used by the Gipity Streamlit application. The function supports UI state management, provider coordination, data normalization, or display behavior required by the surrounding workflow.

Source code in app.py
def unload_docqna_documents( ) -> None:
	"""Unload docqna documents.

        Purpose:
            Provides the unload docqna documents helper used by the Gipity Streamlit application.
            The function supports UI state management, provider coordination, data normalization, or
            display behavior required by the surrounding workflow.
    """
	st.session_state[ 'docqna_uploaded' ] = None
	st.session_state[ 'docqna_files' ] = [ ]
	st.session_state[ 'docqna_active_docs' ] = [ ]
	st.session_state[ 'docqna_bytes' ] = None
	st.session_state[ 'docqna_texts' ] = { }
	st.session_state[ 'docqna_chunks' ] = [ ]
	st.session_state[ 'docqna_vec_ready' ] = False
	st.session_state[ 'docqna_fingerprint' ] = ''
	st.session_state[ 'docqna_chunk_count' ] = 0
	st.session_state[ 'docqna_index_status' ] = 'Not indexed'
	clear_docqna_outputs( )

reset_docqna_controls

reset_docqna_controls() -> None

Reset docqna controls.

Purpose

Resets the docqna controls state used by the application. The function clears related Streamlit keys without performing provider calls.

Source code in app.py
def reset_docqna_controls( ) -> None:
	"""Reset docqna controls.

        Purpose:
            Resets the docqna controls state used by the application. The function clears related
            Streamlit keys without performing provider calls.
    """
	for key in [ 'docqna_model', 'docqna_source', 'docqna_file_id', 'docqna_vector_store_id',
	             'docqna_multi_mode', 'docqna_top_k', 'docqna_chunk_size', 'docqna_chunk_overlap',
	             'docqna_show_diagnostics' ]:
		if key in st.session_state:
			del st.session_state[ key ]

reset_docqna_all

reset_docqna_all() -> None

Reset docqna all.

Purpose

Resets the docqna all state used by the application. The function clears related Streamlit keys without performing provider calls.

Source code in app.py
def reset_docqna_all( ) -> None:
	"""Reset docqna all.

        Purpose:
            Resets the docqna all state used by the application. The function clears related
            Streamlit keys without performing provider calls.
    """
	reset_docqna_controls( )
	unload_docqna_documents( )
	clear_docqna_messages( )

clear_docqna_instructions

clear_docqna_instructions() -> None

Clear docqna instructions.

Purpose

Clears the docqna instructions state used by the current workflow so the user interface can start from a clean output state.

Source code in app.py
def clear_docqna_instructions( ) -> None:
	"""Clear docqna instructions.

        Purpose:
            Clears the docqna instructions state used by the current workflow so the user interface
            can start from a clean output state.
    """
	st.session_state[ 'docqna_system_instructions' ] = ''
	st.session_state[ 'instructions' ] = ''

load_docqna_instruction_template

load_docqna_instruction_template() -> None

Load docqna instruction template.

Purpose

Loads the docqna instruction template resource or state required by the Gipity workflow and returns the prepared value for caller use.

Source code in app.py
def load_docqna_instruction_template( ) -> None:
	"""Load docqna instruction template.

        Purpose:
            Loads the docqna instruction template resource or state required by the Gipity workflow
            and returns the prepared value for caller use.
    """
	name = st.session_state.get( 'instructions' )
	if name and name != 'No Templates Found':
		text = fetch_prompt_text( cfg.DB_PATH, name )
		if text is not None:
			st.session_state[ 'docqna_system_instructions' ] = text

convert_docqna_system_instructions

convert_docqna_system_instructions() -> None

Convert docqna system instructions.

Purpose

Provides the convert docqna system instructions helper used by the Gipity Streamlit application. The function supports UI state management, provider coordination, data normalization, or display behavior required by the surrounding workflow.

Source code in app.py
def convert_docqna_system_instructions( ) -> None:
	"""Convert docqna system instructions.

        Purpose:
            Provides the convert docqna system instructions helper used by the Gipity Streamlit
            application. The function supports UI state management, provider coordination, data
            normalization, or display behavior required by the surrounding workflow.
    """
	text = st.session_state.get( 'docqna_system_instructions', '' )
	if not isinstance( text, str ) or not text.strip( ):
		return
	source = text.strip( )
	if cfg.XML_BLOCK_PATTERN.search( source ):
		converted = convert_xml( source )
	else:
		converted = convert_markdown( source )
	st.session_state[ 'docqna_system_instructions' ] = converted

get_docqna_source_options

get_docqna_source_options() -> List[str]

Get docqna source options.

Purpose

Returns the docqna source options value used by the Gipity interface. The helper centralizes option lookup and fallback behavior for callers.

Returns:

Type Description
List[str]

Value produced by the get_docqna_source_options helper according to its function

List[str]

annotation and return statements.

Source code in app.py
def get_docqna_source_options( ) -> List[ str ]:
	"""Get docqna source options.

        Purpose:
            Returns the docqna source options value used by the Gipity interface. The helper
            centralizes option lookup and fallback behavior for callers.

        Returns:
            Value produced by the get_docqna_source_options helper according to its function
            annotation and return statements.
    """
	return [ 'Local Upload', 'OpenAI File ID', 'OpenAI Vector Store ID' ]

get_docqna_file_extension

get_docqna_file_extension(filename: str | None) -> str

Get docqna file extension.

Purpose

Returns the docqna file extension value used by the Gipity interface. The helper centralizes option lookup and fallback behavior for callers.

Parameters:

Name Type Description Default
filename str | None

Value supplied to the helper.

required

Returns:

Type Description
str

Value produced by the get_docqna_file_extension helper according to its function

str

annotation and return statements.

Source code in app.py
def get_docqna_file_extension( filename: str | None ) -> str:
	"""Get docqna file extension.

        Purpose:
            Returns the docqna file extension value used by the Gipity interface. The helper
            centralizes option lookup and fallback behavior for callers.

        Args:
            filename (str | None): Value supplied to the helper.

        Returns:
            Value produced by the get_docqna_file_extension helper according to its function
            annotation and return statements.
    """
	if not isinstance( filename, str ) or not filename.strip( ):
		return ''
	return Path( filename ).suffix.lower( )

compute_docqna_fingerprint

compute_docqna_fingerprint(
    documents: List[Dict[str, Any]],
) -> str

Compute docqna fingerprint.

Purpose

Provides the compute docqna fingerprint helper used by the Gipity Streamlit application. The function supports UI state management, provider coordination, data normalization, or display behavior required by the surrounding workflow.

Parameters:

Name Type Description Default
documents List[Dict[str, Any]]

Value supplied to the helper.

required

Returns:

Type Description
str

Value produced by the compute_docqna_fingerprint helper according to its function

str

annotation and return statements.

Source code in app.py
def compute_docqna_fingerprint( documents: List[ Dict[ str, Any ] ] ) -> str:
	"""Compute docqna fingerprint.

        Purpose:
            Provides the compute docqna fingerprint helper used by the Gipity Streamlit application.
            The function supports UI state management, provider coordination, data normalization, or
            display behavior required by the surrounding workflow.

        Args:
            documents (List[Dict[str, Any]]): Value supplied to the helper.

        Returns:
            Value produced by the compute_docqna_fingerprint helper according to its function
            annotation and return statements.
    """
	hasher = hashlib.sha256( )
	if not isinstance( documents, list ):
		return ''
	for doc in documents:
		if not isinstance( doc, dict ):
			continue
		name = str( doc.get( 'name', '' ) )
		content = doc.get( 'bytes', b'' )
		hasher.update( name.encode( 'utf-8', errors='ignore' ) )
		if isinstance( content, bytes ):
			hasher.update( content )
	return hasher.hexdigest( )

compute_fingerprint

compute_fingerprint(file_bytes: bytes | None) -> str

Compute fingerprint.

Purpose

Provides the compute fingerprint helper used by the Gipity Streamlit application. The function supports UI state management, provider coordination, data normalization, or display behavior required by the surrounding workflow.

Parameters:

Name Type Description Default
file_bytes bytes | None

Value supplied to the helper.

required

Returns:

Type Description
str

Value produced by the compute_fingerprint helper according to its function annotation

str

and return statements.

Source code in app.py
def compute_fingerprint( file_bytes: bytes | None ) -> str:
	"""Compute fingerprint.

        Purpose:
            Provides the compute fingerprint helper used by the Gipity Streamlit application. The
            function supports UI state management, provider coordination, data normalization, or
            display behavior required by the surrounding workflow.

        Args:
            file_bytes (bytes | None): Value supplied to the helper.

        Returns:
            Value produced by the compute_fingerprint helper according to its function annotation
            and return statements.
    """
	if not isinstance( file_bytes, bytes ):
		return ''
	return hashlib.sha256( file_bytes ).hexdigest( )

load_docqna_uploaded_files

load_docqna_uploaded_files(
    uploaded: Any,
) -> List[Dict[str, Any]]

Load docqna uploaded files.

Purpose

Loads the docqna uploaded files resource or state required by the Gipity workflow and returns the prepared value for caller use.

Parameters:

Name Type Description Default
uploaded Any

Value supplied to the helper.

required

Returns:

Type Description
List[Dict[str, Any]]

Value produced by the load_docqna_uploaded_files helper according to its function

List[Dict[str, Any]]

annotation and return statements.

Source code in app.py
def load_docqna_uploaded_files( uploaded: Any ) -> List[ Dict[ str, Any ] ]:
	"""Load docqna uploaded files.

        Purpose:
            Loads the docqna uploaded files resource or state required by the Gipity workflow and
            returns the prepared value for caller use.

        Args:
            uploaded (Any): Value supplied to the helper.

        Returns:
            Value produced by the load_docqna_uploaded_files helper according to its function
            annotation and return statements.
    """
	if uploaded is None:
		return [ ]
	files = uploaded if isinstance( uploaded, list ) else [ uploaded ]
	active_docs: List[ Dict[ str, Any ] ] = [ ]
	texts: Dict[ str, str ] = { }
	for item in files:
		if item is None:
			continue
		name = getattr( item, 'name', 'uploaded_document' )
		try:
			content = item.getvalue( ) if hasattr( item, 'getvalue' ) else item.read( )
		except Exception as e:
			exception = Error( e )
			exception.module = 'app'
			exception.cause = 'load_docqna_uploaded_files'
			exception.method = 'load_docqna_uploaded_files( ... )'
			Logger( ).write( exception )
			content = None
		if not isinstance( content, bytes ) or len( content ) == 0:
			continue
		text = extract_docqna_text( filename=name, file_bytes=content )
		active_docs.append(
			{ 'name': name, 'extension': get_docqna_file_extension( name ), 'bytes': content,
			  'text': text, 'size': len( content ) } )
		texts[ name ] = text
	st.session_state[ 'docqna_uploaded' ] = uploaded
	st.session_state[ 'docqna_files' ] = active_docs
	st.session_state[ 'docqna_active_docs' ] = active_docs
	st.session_state[ 'docqna_texts' ] = texts
	if len( active_docs ) == 1:
		st.session_state[ 'docqna_bytes' ] = active_docs[ 0 ].get( 'bytes' )
		st.session_state[ 'doc_bytes' ] = active_docs[ 0 ].get( 'bytes' )
	elif len( active_docs ) > 1:
		st.session_state[ 'docqna_bytes' ] = active_docs[ 0 ].get( 'bytes' )
		st.session_state[ 'doc_bytes' ] = active_docs[ 0 ].get( 'bytes' )
	fingerprint = compute_docqna_fingerprint( active_docs )
	if fingerprint != st.session_state.get( 'docqna_fingerprint', '' ):
		st.session_state[ 'docqna_vec_ready' ] = False
		st.session_state[ 'docqna_fingerprint' ] = fingerprint
		st.session_state[ 'docqna_index_status' ] = 'Loaded; not indexed'
	return active_docs

get_docqna_active_document_names

get_docqna_active_document_names() -> List[str]

Get docqna active document names.

Purpose

Returns the docqna active document names value used by the Gipity interface. The helper centralizes option lookup and fallback behavior for callers.

Returns:

Type Description
List[str]

Value produced by the get_docqna_active_document_names helper according to its function

List[str]

annotation and return statements.

Source code in app.py
def get_docqna_active_document_names( ) -> List[ str ]:
	"""Get docqna active document names.

        Purpose:
            Returns the docqna active document names value used by the Gipity interface. The helper
            centralizes option lookup and fallback behavior for callers.

        Returns:
            Value produced by the get_docqna_active_document_names helper according to its function
            annotation and return statements.
    """
	docs = st.session_state.get( 'docqna_active_docs', [ ] )
	if not isinstance( docs, list ):
		return [ ]
	return [ doc.get( 'name', '' ) for doc in docs if
	         isinstance( doc, dict ) and doc.get( 'name' ) ]

get_docqna_active_bytes

get_docqna_active_bytes() -> bytes | None

Get docqna active bytes.

Purpose

Returns the docqna active bytes value used by the Gipity interface. The helper centralizes option lookup and fallback behavior for callers.

Returns:

Type Description
bytes | None

Value produced by the get_docqna_active_bytes helper according to its function

bytes | None

annotation and return statements.

Source code in app.py
def get_docqna_active_bytes( ) -> bytes | None:
	"""Get docqna active bytes.

        Purpose:
            Returns the docqna active bytes value used by the Gipity interface. The helper
            centralizes option lookup and fallback behavior for callers.

        Returns:
            Value produced by the get_docqna_active_bytes helper according to its function
            annotation and return statements.
    """
	value = st.session_state.get( 'docqna_bytes', None )
	if isinstance( value, bytes ):
		return value
	legacy = st.session_state.get( 'doc_bytes', None )
	if isinstance( legacy, bytes ):
		st.session_state[ 'docqna_bytes' ] = legacy
		return legacy
	return None

render_docqna_document_preview

render_docqna_document_preview() -> None

Render docqna document preview.

Purpose

Renders the docqna document preview user-interface section or display element in Streamlit while preserving the application state expected by the surrounding workflow.

Source code in app.py
def render_docqna_document_preview( ) -> None:
	"""Render docqna document preview.

        Purpose:
            Renders the docqna document preview user-interface section or display element in
            Streamlit while preserving the application state expected by the surrounding workflow.
    """
	docs = st.session_state.get( 'docqna_active_docs', [ ] )
	for doc in docs:
		if not isinstance( doc, dict ):
			continue
		name = doc.get( 'name', 'Document' )
		extension = doc.get( 'extension', '' )
		content = doc.get( 'bytes', b'' )
		text = doc.get( 'text', '' )
		with st.expander( label=f'Preview: {name}', icon='📄', expanded=False, width='stretch' ):
			st.caption(
				f"File type: {extension or 'unknown'} | Size: {doc.get( 'size', 0 )} bytes" )
			if extension == '.pdf' and isinstance( content, bytes ):
				try:
					st.pdf( content, height=420 )
				except Exception as e:
					exception = Error( e )
					exception.module = 'app'
					exception.cause = 'render_docqna_document_preview'
					exception.method = 'render_docqna_document_preview( ... )'
					Logger( ).write( exception )
					st.text_area( label='Extracted Text Preview',
						value=text[ :12000 ] if isinstance( text, str ) else '', height=300,
						width='stretch', disabled=True )
			elif extension == '.md' and isinstance( text, str ):
				st.markdown( text[ :12000 ] )
			elif isinstance( text, str ) and text.strip( ):
				st.text_area( label='Extracted Text Preview', value=text[ :12000 ], height=300,
					width='stretch', disabled=True )
			else:
				st.warning( 'No readable text preview is available for this file.' )

normalize_docqna_text

normalize_docqna_text(text: str) -> str

Normalize docqna text.

Purpose

Normalizes the docqna text input into the stable shape expected by downstream Gipity helpers and display logic.

Parameters:

Name Type Description Default
text str

Value supplied to the helper.

required

Returns:

Type Description
str

Value produced by the normalize_docqna_text helper according to its function annotation

str

and return statements.

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

        Purpose:
            Normalizes the docqna text input into the stable shape expected by downstream Gipity
            helpers and display logic.

        Args:
            text (str): Value supplied to the helper.

        Returns:
            Value produced by the normalize_docqna_text helper according to its function annotation
            and return statements.
    """
	if not isinstance( text, str ):
		return ''
	value = text.replace( '\x00', ' ' )
	value = re.sub( '[ \\t]+', ' ', value )
	value = re.sub( '\\n{3,}', '\n\n', value )
	return value.strip( )

chunk_docqna_text

chunk_docqna_text(
    text: str,
    chunk_size: int = 900,
    chunk_overlap: int = 150,
) -> List[str]

Chunk docqna text.

Purpose

Provides the chunk docqna text helper used by the Gipity Streamlit application. The function supports UI state management, provider coordination, data normalization, or display behavior required by the surrounding workflow.

Parameters:

Name Type Description Default
text str

Value supplied to the helper.

required
chunk_size int

Value supplied to the helper.

900
chunk_overlap int

Value supplied to the helper.

150

Returns:

Type Description
List[str]

Value produced by the chunk_docqna_text helper according to its function annotation and

List[str]

return statements.

Source code in app.py
def chunk_docqna_text( text: str, chunk_size: int=900, chunk_overlap: int=150 ) -> List[ str ]:
	"""Chunk docqna text.

        Purpose:
            Provides the chunk docqna text helper used by the Gipity Streamlit application. The
            function supports UI state management, provider coordination, data normalization, or
            display behavior required by the surrounding workflow.

        Args:
            text (str): Value supplied to the helper.
            chunk_size (int): Value supplied to the helper.
            chunk_overlap (int): Value supplied to the helper.

        Returns:
            Value produced by the chunk_docqna_text helper according to its function annotation and
            return statements.
    """
	if not isinstance( text, str ) or not text.strip( ):
		return [ ]
	try:
		size = int( chunk_size )
	except Exception as e:
		exception = Error( e )
		exception.module = 'app'
		exception.cause = 'chunk_docqna_text'
		exception.method = 'chunk_docqna_text( ... )'
		Logger( ).write( exception )
		size = 900
	try:
		overlap = int( chunk_overlap )
	except Exception as e:
		exception = Error( e )
		exception.module = 'app'
		exception.cause = 'chunk_docqna_text'
		exception.method = 'chunk_docqna_text( ... )'
		Logger( ).write( exception )
		overlap = 150
	if size <= 0:
		size = 900
	if overlap < 0:
		overlap = 0
	if overlap >= size:
		overlap = max( 0, size // 5 )
	words = text.split( )
	if len( words ) == 0:
		return [ ]
	chunks: List[ str ] = [ ]
	step = max( 1, size - overlap )
	start = 0
	while start < len( words ):
		end = min( start + size, len( words ) )
		chunk = ' '.join( words[ start:end ] ).strip( )
		if chunk:
			chunks.append( chunk )
		if end >= len( words ):
			break
		start += step
	return chunks

rebuild_docqna_index

rebuild_docqna_index() -> List[Dict[str, Any]]

Rebuild docqna index.

Purpose

Provides the rebuild docqna index helper used by the Gipity Streamlit application. The function supports UI state management, provider coordination, data normalization, or display behavior required by the surrounding workflow.

Returns:

Type Description
List[Dict[str, Any]]

Value produced by the rebuild_docqna_index helper according to its function annotation

List[Dict[str, Any]]

and return statements.

Source code in app.py
def rebuild_docqna_index( ) -> List[ Dict[ str, Any ] ]:
	"""Rebuild docqna index.

        Purpose:
            Provides the rebuild docqna index helper used by the Gipity Streamlit application. The
            function supports UI state management, provider coordination, data normalization, or
            display behavior required by the surrounding workflow.

        Returns:
            Value produced by the rebuild_docqna_index helper according to its function annotation
            and return statements.
    """
	docs = st.session_state.get( 'docqna_active_docs', [ ] )
	if not isinstance( docs, list ) or len( docs ) == 0:
		st.session_state[ 'docqna_chunks' ] = [ ]
		st.session_state[ 'docqna_vec_ready' ] = False
		st.session_state[ 'docqna_chunk_count' ] = 0
		st.session_state[ 'docqna_index_status' ] = 'No documents loaded'
		return [ ]
	chunk_records: List[ Dict[ str, Any ] ] = [ ]
	chunk_size = st.session_state.get( 'docqna_chunk_size', 900 )
	chunk_overlap = st.session_state.get( 'docqna_chunk_overlap', 150 )
	for doc in docs:
		if not isinstance( doc, dict ):
			continue
		name = doc.get( 'name', 'Document' )
		text = normalize_docqna_text( doc.get( 'text', '' ) )
		for index, chunk in enumerate( chunk_docqna_text( text=text, chunk_size=chunk_size,
				chunk_overlap=chunk_overlap ) ):
			chunk_records.append( { 'document': name, 'chunk_index': index + 1, 'text': chunk } )
	st.session_state[ 'docqna_chunks' ] = chunk_records
	st.session_state[ 'docqna_chunk_count' ] = len( chunk_records )
	st.session_state[ 'docqna_vec_ready' ] = len( chunk_records ) > 0
	st.session_state[ 'docqna_index_status' ] = 'Ready' if len(
		chunk_records ) > 0 else 'No text extracted'
	return chunk_records

tokenize_docqna_query

tokenize_docqna_query(text: str) -> List[str]

Tokenize docqna query.

Purpose

Provides the tokenize docqna query helper used by the Gipity Streamlit application. The function supports UI state management, provider coordination, data normalization, or display behavior required by the surrounding workflow.

Parameters:

Name Type Description Default
text str

Value supplied to the helper.

required

Returns:

Type Description
List[str]

Value produced by the tokenize_docqna_query helper according to its function annotation

List[str]

and return statements.

Source code in app.py
def tokenize_docqna_query( text: str ) -> List[ str ]:
	"""Tokenize docqna query.

        Purpose:
            Provides the tokenize docqna query helper used by the Gipity Streamlit application. The
            function supports UI state management, provider coordination, data normalization, or
            display behavior required by the surrounding workflow.

        Args:
            text (str): Value supplied to the helper.

        Returns:
            Value produced by the tokenize_docqna_query helper according to its function annotation
            and return statements.
    """
	if not isinstance( text, str ):
		return [ ]
	return re.findall( '[A-Za-z0-9_]+', text.lower( ) )

score_docqna_chunk

score_docqna_chunk(
    query_tokens: List[str], chunk_text: str
) -> float

Score docqna chunk.

Purpose

Provides the score docqna chunk helper used by the Gipity Streamlit application. The function supports UI state management, provider coordination, data normalization, or display behavior required by the surrounding workflow.

Parameters:

Name Type Description Default
query_tokens List[str]

Value supplied to the helper.

required
chunk_text str

Value supplied to the helper.

required

Returns:

Type Description
float

Value produced by the score_docqna_chunk helper according to its function annotation and

float

return statements.

Source code in app.py
def score_docqna_chunk( query_tokens: List[ str ], chunk_text: str ) -> float:
	"""Score docqna chunk.

        Purpose:
            Provides the score docqna chunk helper used by the Gipity Streamlit application. The
            function supports UI state management, provider coordination, data normalization, or
            display behavior required by the surrounding workflow.

        Args:
            query_tokens (List[str]): Value supplied to the helper.
            chunk_text (str): Value supplied to the helper.

        Returns:
            Value produced by the score_docqna_chunk helper according to its function annotation and
            return statements.
    """
	if not isinstance( query_tokens, list ) or len( query_tokens ) == 0:
		return 0.0
	chunk_tokens = tokenize_docqna_query( chunk_text )
	if len( chunk_tokens ) == 0:
		return 0.0
	query_counts: Dict[ str, int ] = { }
	chunk_counts: Dict[ str, int ] = { }
	for token in query_tokens:
		query_counts[ token ] = query_counts.get( token, 0 ) + 1
	for token in chunk_tokens:
		chunk_counts[ token ] = chunk_counts.get( token, 0 ) + 1
	dot = sum(
		(query_counts.get( token, 0 ) * chunk_counts.get( token, 0 ) for token in query_counts) )
	query_norm = math.sqrt( sum( (value * value for value in query_counts.values( )) ) )
	chunk_norm = math.sqrt( sum( (value * value for value in chunk_counts.values( )) ) )
	if query_norm == 0 or chunk_norm == 0:
		return 0.0
	return dot / (query_norm * chunk_norm)

retrieve_docqna_chunks

retrieve_docqna_chunks(
    query: str, top_k: int | None = None
) -> List[Dict[str, Any]]

Retrieve docqna chunks.

Purpose

Provides the retrieve docqna chunks helper used by the Gipity Streamlit application. The function supports UI state management, provider coordination, data normalization, or display behavior required by the surrounding workflow.

Parameters:

Name Type Description Default
query str

Value supplied to the helper.

required
top_k int | None

Value supplied to the helper.

None

Returns:

Type Description
List[Dict[str, Any]]

Value produced by the retrieve_docqna_chunks helper according to its function annotation

List[Dict[str, Any]]

and return statements.

Source code in app.py
def retrieve_docqna_chunks( query: str, top_k: int | None=None ) -> List[ Dict[ str, Any ] ]:
	"""Retrieve docqna chunks.

        Purpose:
            Provides the retrieve docqna chunks helper used by the Gipity Streamlit application. The
            function supports UI state management, provider coordination, data normalization, or
            display behavior required by the surrounding workflow.

        Args:
            query (str): Value supplied to the helper.
            top_k (int | None): Value supplied to the helper.

        Returns:
            Value produced by the retrieve_docqna_chunks helper according to its function annotation
            and return statements.
    """
	if not st.session_state.get( 'docqna_vec_ready', False ):
		rebuild_docqna_index( )
	chunks = st.session_state.get( 'docqna_chunks', [ ] )
	if not isinstance( chunks, list ) or len( chunks ) == 0:
		return [ ]
	try:
		k = int( top_k if top_k is not None else st.session_state.get( 'docqna_top_k', 6 ) )
	except Exception as e:
		exception = Error( e )
		exception.module = 'app'
		exception.cause = 'retrieve_docqna_chunks'
		exception.method = 'retrieve_docqna_chunks( ... )'
		Logger( ).write( exception )
		k = 6
	if k <= 0:
		k = 6
	query_tokens = tokenize_docqna_query( query )
	hits: List[ Dict[ str, Any ] ] = [ ]
	for chunk in chunks:
		if not isinstance( chunk, dict ):
			continue
		score = score_docqna_chunk( query_tokens, chunk.get( 'text', '' ) )
		hits.append( { 'rank': 0, 'document': chunk.get( 'document', '' ),
		               'chunk_index': chunk.get( 'chunk_index', 0 ), 'score': round( score, 6 ),
		               'text': chunk.get( 'text', '' ) } )
	hits = sorted( hits, key=lambda item: item.get( 'score', 0.0 ), reverse=True )[ :k ]
	for index, hit in enumerate( hits ):
		hit[ 'rank' ] = index + 1
	st.session_state[ 'docqna_last_hits' ] = hits
	st.session_state[ 'docqna_last_sources' ] = [
			{ 'document': hit.get( 'document', '' ), 'chunk_index': hit.get( 'chunk_index', 0 ),
			  'score': hit.get( 'score', 0.0 ) } for hit in hits ]
	st.session_state[ 'last_sources' ] = st.session_state[ 'docqna_last_sources' ]
	return hits

build_docqna_local_prompt

build_docqna_local_prompt(
    query: str, hits: List[Dict[str, Any]]
) -> str

Build docqna local prompt.

Purpose

Builds the docqna local prompt value used by the Gipity interface or provider wrapper. The function normalizes inputs and returns a stable object for downstream use.

Parameters:

Name Type Description Default
query str

Value supplied to the helper.

required
hits List[Dict[str, Any]]

Value supplied to the helper.

required

Returns:

Type Description
str

Value produced by the build_docqna_local_prompt helper according to its function

str

annotation and return statements.

Source code in app.py
def build_docqna_local_prompt( query: str, hits: List[ Dict[ str, Any ] ] ) -> str:
	"""Build docqna local prompt.

        Purpose:
            Builds the docqna local prompt value used by the Gipity interface or provider wrapper.
            The function normalizes inputs and returns a stable object for downstream use.

        Args:
            query (str): Value supplied to the helper.
            hits (List[Dict[str, Any]]): Value supplied to the helper.

        Returns:
            Value produced by the build_docqna_local_prompt helper according to its function
            annotation and return statements.
    """
	context_blocks: List[ str ] = [ ]
	for hit in hits:
		if not isinstance( hit, dict ):
			continue
		context_blocks.append(
			f"[Source: {hit.get( 'document', '' )}, Chunk: {hit.get( 'chunk_index', 0 )}, Score: {hit.get( 'score', 0.0 )}]\n{hit.get( 'text', '' )}" )
	context = '\n\n---\n\n'.join( context_blocks )
	st.session_state[ 'docqna_context' ] = context
	instructions = st.session_state.get( 'docqna_system_instructions', '' )
	return (f'{instructions.strip( )}\n\n' if isinstance( instructions,
		str ) and instructions.strip( ) else '') + f'Answer the user question using only the document context below. If the answer is not supported by the context, say that the document context does not contain enough information.\n\nDocument Context:\n{context}\n\nUser Question:\n{query}'

docqna_call_openai_text_model

docqna_call_openai_text_model(prompt: str) -> str

Docqna call openai text model.

Purpose

Provides the docqna call openai text model helper used by the Gipity Streamlit application. The function supports UI state management, provider coordination, data normalization, or display behavior required by the surrounding workflow.

Parameters:

Name Type Description Default
prompt str

Value supplied to the helper.

required

Returns:

Type Description
str

Value produced by the docqna_call_openai_text_model helper according to its function

str

annotation and return statements.

Source code in app.py
def docqna_call_openai_text_model( prompt: str ) -> str:
	"""Docqna call openai text model.

        Purpose:
            Provides the docqna call openai text model helper used by the Gipity Streamlit
            application. The function supports UI state management, provider coordination, data
            normalization, or display behavior required by the surrounding workflow.

        Args:
            prompt (str): Value supplied to the helper.

        Returns:
            Value produced by the docqna_call_openai_text_model helper according to its function
            annotation and return statements.
    """
	if not isinstance( prompt, str ) or not prompt.strip( ):
		return ''
	model = st.session_state.get( 'docqna_model' ) or 'gpt-4o-mini'
	try:
		run_turn = globals( ).get( 'run_llm_turn' )
		if callable( run_turn ):
			return str( run_turn( prompt=prompt, model=model,
				temperature=st.session_state.get( 'docqna_temperature', 0.2 ),
				top_p=st.session_state.get( 'docqna_top_percent', 1.0 ),
				max_tokens=st.session_state.get( 'docqna_max_tokens', 2000 ) ) )
	except Exception as e:
		exception = Error( e )
		exception.module = 'app'
		exception.cause = 'docqna_call_openai_text_model'
		exception.method = 'docqna_call_openai_text_model( ... )'
		Logger( ).write( exception )
		pass
	try:
		chat = Chat( )
		for method_name in [ 'generate_text', 'create', 'ask', 'complete' ]:
			method = getattr( chat, method_name, None )
			if callable( method ):
				try:
					result = method( text=prompt, model=model )
				except TypeError as e:
					exception = Error( e )
					exception.module = 'app'
					exception.cause = 'docqna_call_openai_text_model'
					exception.method = 'docqna_call_openai_text_model( ... )'
					Logger( ).write( exception )
					try:
						result = method( prompt=prompt, model=model )
					except TypeError as e:
						exception = Error( e )
						exception.module = 'app'
						exception.cause = 'docqna_call_openai_text_model'
						exception.method = 'docqna_call_openai_text_model( ... )'
						Logger( ).write( exception )
						result = method( prompt )
				return str( getattr( result, 'output_text', result ) )
	except Exception as exc:
		exception = Error( exc )
		exception.module = 'app'
		exception.cause = 'docqna_call_openai_text_model'
		exception.method = 'docqna_call_openai_text_model( ... )'
		Logger( ).write( exception )
		return f'Document Q&A model call failed: {exc}'
	return prompt

run_docqna_local_query

run_docqna_local_query(query: str) -> str

Run docqna local query.

Purpose

Runs the docqna local query workflow from the Streamlit interface by validating current inputs, calling the appropriate wrapper or helper, and storing relevant output state.

Parameters:

Name Type Description Default
query str

Value supplied to the helper.

required

Returns:

Type Description
str

Value produced by the run_docqna_local_query helper according to its function annotation

str

and return statements.

Source code in app.py
def run_docqna_local_query( query: str ) -> str:
	"""Run docqna local query.

        Purpose:
            Runs the docqna local query workflow from the Streamlit interface by validating current
            inputs, calling the appropriate wrapper or helper, and storing relevant output state.

        Args:
            query (str): Value supplied to the helper.

        Returns:
            Value produced by the run_docqna_local_query helper according to its function annotation
            and return statements.
    """
	if not isinstance( query, str ) or not query.strip( ):
		return ''
	if not st.session_state.get( 'docqna_vec_ready', False ):
		rebuild_docqna_index( )
	hits = retrieve_docqna_chunks( query=query, top_k=st.session_state.get( 'docqna_top_k', 6 ) )
	if len( hits ) == 0:
		answer = 'No readable or retrievable document context is available.'
		st.session_state[ 'docqna_last_answer' ] = answer
		st.session_state[ 'last_answer' ] = answer
		return answer
	prompt = build_docqna_local_prompt( query=query, hits=hits )
	answer = docqna_call_openai_text_model( prompt )
	st.session_state[ 'docqna_last_answer' ] = answer
	st.session_state[ 'last_answer' ] = answer
	return answer

run_docqna_file_query

run_docqna_file_query(query: str) -> str

Run docqna file query.

Purpose

Runs the docqna file query workflow from the Streamlit interface by validating current inputs, calling the appropriate wrapper or helper, and storing relevant output state.

Parameters:

Name Type Description Default
query str

Value supplied to the helper.

required

Returns:

Type Description
str

Value produced by the run_docqna_file_query helper according to its function annotation

str

and return statements.

Source code in app.py
def run_docqna_file_query( query: str ) -> str:
	"""Run docqna file query.

        Purpose:
            Runs the docqna file query workflow from the Streamlit interface by validating current
            inputs, calling the appropriate wrapper or helper, and storing relevant output state.

        Args:
            query (str): Value supplied to the helper.

        Returns:
            Value produced by the run_docqna_file_query helper according to its function annotation
            and return statements.
    """
	file_id = st.session_state.get( 'docqna_file_id', '' )
	if not isinstance( file_id, str ) or not file_id.strip( ):
		return 'No OpenAI file ID is selected.'
	try:
		files = Files( )
		answer = files.search( id=file_id.strip( ), query=query,
			model=st.session_state.get( 'docqna_model' ) or 'gpt-4o-mini' )
		answer = answer if isinstance( answer, str ) else str( answer )
		st.session_state[ 'docqna_last_answer' ] = answer
		st.session_state[ 'last_answer' ] = answer
		st.session_state[ 'docqna_last_sources' ] = [ { 'file_id': file_id.strip( ) } ]
		st.session_state[ 'last_sources' ] = st.session_state[ 'docqna_last_sources' ]
		return answer
	except Exception as exc:
		exception = Error( exc )
		exception.module = 'app'
		exception.cause = 'run_docqna_file_query'
		exception.method = 'run_docqna_file_query( ... )'
		Logger( ).write( exception )
		return f'OpenAI file query failed: {exc}'

run_docqna_vector_store_query

run_docqna_vector_store_query(query: str) -> str

Run docqna vector store query.

Purpose

Runs the docqna vector store query workflow from the Streamlit interface by validating current inputs, calling the appropriate wrapper or helper, and storing relevant output state.

Parameters:

Name Type Description Default
query str

Value supplied to the helper.

required

Returns:

Type Description
str

Value produced by the run_docqna_vector_store_query helper according to its function

str

annotation and return statements.

Source code in app.py
def run_docqna_vector_store_query( query: str ) -> str:
	"""Run docqna vector store query.

        Purpose:
            Runs the docqna vector store query workflow from the Streamlit interface by validating
            current inputs, calling the appropriate wrapper or helper, and storing relevant output
            state.

        Args:
            query (str): Value supplied to the helper.

        Returns:
            Value produced by the run_docqna_vector_store_query helper according to its function
            annotation and return statements.
    """
	store_id = st.session_state.get( 'docqna_vector_store_id', '' )
	if not isinstance( store_id, str ) or not store_id.strip( ):
		return 'No OpenAI vector store ID is selected.'
	try:
		vector = VectorStores( )
		answer = vector.answer_with_file_search( store_ids=[ store_id.strip( ) ], prompt=query,
			model=st.session_state.get( 'docqna_model' ) or 'gpt-4o-mini',
			max_num_results=st.session_state.get( 'docqna_top_k', 6 ),
			instructions=st.session_state.get( 'docqna_system_instructions', '' ) or None )
		answer = answer if isinstance( answer, str ) else str( answer )
		st.session_state[ 'docqna_last_answer' ] = answer
		st.session_state[ 'last_answer' ] = answer
		st.session_state[ 'docqna_last_sources' ] = [ { 'vector_store_id': store_id.strip( ) } ]
		st.session_state[ 'last_sources' ] = st.session_state[ 'docqna_last_sources' ]
		return answer
	except Exception as exc:
		exception = Error( exc )
		exception.module = 'app'
		exception.cause = 'run_docqna_vector_store_query'
		exception.method = 'run_docqna_vector_store_query( ... )'
		Logger( ).write( exception )
		return f'OpenAI vector store query failed: {exc}'

route_document_query

route_document_query(prompt: str) -> str

Route document query.

Purpose

Provides the route document query helper used by the Gipity Streamlit application. The function supports UI state management, provider coordination, data normalization, or display behavior required by the surrounding workflow.

Parameters:

Name Type Description Default
prompt str

Value supplied to the helper.

required

Returns:

Type Description
str

Value produced by the route_document_query helper according to its function annotation

str

and return statements.

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

        Purpose:
            Provides the route document query helper used by the Gipity Streamlit application. The
            function supports UI state management, provider coordination, data normalization, or
            display behavior required by the surrounding workflow.

        Args:
            prompt (str): Value supplied to the helper.

        Returns:
            Value produced by the route_document_query helper according to its function annotation
            and return statements.
    """
	if not isinstance( prompt, str ) or not prompt.strip( ):
		return ''
	source = st.session_state.get( 'docqna_source', 'Local Upload' )
	if source == 'OpenAI File ID':
		return run_docqna_file_query( prompt )
	if source == 'OpenAI Vector Store ID':
		return run_docqna_vector_store_query( prompt )
	return run_docqna_local_query( prompt )

summarize_active_document

summarize_active_document() -> str

Summarize active document.

Purpose

Provides the summarize active document helper used by the Gipity Streamlit application. The function supports UI state management, provider coordination, data normalization, or display behavior required by the surrounding workflow.

Returns:

Type Description
str

Value produced by the summarize_active_document helper according to its function

str

annotation and return statements.

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

        Purpose:
            Provides the summarize active document helper used by the Gipity Streamlit application.
            The function supports UI state management, provider coordination, data normalization, or
            display behavior required by the surrounding workflow.

        Returns:
            Value produced by the summarize_active_document helper according to its function
            annotation and return statements.
    """
	return route_document_query(
		'Summarize the active document. Include the main topic, key sections, important findings, and any limitations visible in the source.' )

render_docqna_retrieval_hits

render_docqna_retrieval_hits() -> None

Render docqna retrieval hits.

Purpose

Renders the docqna retrieval hits user-interface section or display element in Streamlit while preserving the application state expected by the surrounding workflow.

Source code in app.py
def render_docqna_retrieval_hits( ) -> None:
	"""Render docqna retrieval hits.

        Purpose:
            Renders the docqna retrieval hits user-interface section or display element in Streamlit
            while preserving the application state expected by the surrounding workflow.
    """
	hits = st.session_state.get( 'docqna_last_hits', [ ] )
	if not isinstance( hits, list ) or len( hits ) == 0:
		st.info( 'No retrieval hits available.' )
		return
	df_hits = pd.DataFrame( hits )
	st.data_editor( df_hits, use_container_width=True, hide_index=True )

render_docqna_status

render_docqna_status() -> None

Render docqna status.

Purpose

Renders the docqna status user-interface section or display element in Streamlit while preserving the application state expected by the surrounding workflow.

Source code in app.py
def render_docqna_status( ) -> None:
	"""Render docqna status.

        Purpose:
            Renders the docqna status user-interface section or display element in Streamlit while
            preserving the application state expected by the surrounding workflow.
    """
	c1, c2, c3, c4 = st.columns( [ 0.25, 0.25, 0.25, 0.25 ], border=True, gap='xxsmall' )
	with c1:
		st.metric( 'Documents', len( get_docqna_active_document_names( ) ) )
	with c2:
		st.metric( 'Chunks', st.session_state.get( 'docqna_chunk_count', 0 ) )
	with c3:
		st.metric( 'Source', st.session_state.get( 'docqna_source', 'Local Upload' ) )
	with c4:
		st.metric( 'Index', st.session_state.get( 'docqna_index_status', 'Not indexed' ) )

ensure_files_mode_state

ensure_files_mode_state() -> None

Ensure files mode state.

Purpose

Ensures the required files mode state session-state keys or runtime resources exist before the related interface controls are rendered.

Source code in app.py
def ensure_files_mode_state( ) -> None:
	"""Ensure files mode state.

        Purpose:
            Ensures the required files mode state session-state keys or runtime resources exist
            before the related interface controls are rendered.
    """
	if 'files_model' not in st.session_state:
		st.session_state[ 'files_model' ] = ''
	if 'files_purpose' not in st.session_state:
		st.session_state[ 'files_purpose' ] = 'user_data'
	if 'files_filter_purpose' not in st.session_state:
		st.session_state[ 'files_filter_purpose' ] = ''
	if 'files_type' not in st.session_state:
		st.session_state[ 'files_type' ] = ''
	if 'files_id' not in st.session_state:
		st.session_state[ 'files_id' ] = ''
	if 'files_url' not in st.session_state:
		st.session_state[ 'files_url' ] = ''
	if 'files_table' not in st.session_state:
		st.session_state[ 'files_table' ] = [ ]
	if 'files_df' not in st.session_state:
		st.session_state[ 'files_df' ] = pd.DataFrame( )
	if 'files_metadata' not in st.session_state:
		st.session_state[ 'files_metadata' ] = { }
	if 'files_content' not in st.session_state:
		st.session_state[ 'files_content' ] = ''
	if 'files_content_bytes' not in st.session_state:
		st.session_state[ 'files_content_bytes' ] = None
	if 'files_delete_result' not in st.session_state:
		st.session_state[ 'files_delete_result' ] = { }
	if 'files_last_answer' not in st.session_state:
		st.session_state[ 'files_last_answer' ] = ''
	if 'files_system_instructions' not in st.session_state:
		st.session_state[ 'files_system_instructions' ] = ''
	if 'files_messages' not in st.session_state:
		st.session_state.files_messages = [ ]
	if not isinstance( st.session_state.get( 'files_messages' ), list ):
		st.session_state.files_messages = [ ]

get_files_upload_purpose_options

get_files_upload_purpose_options(files: Files) -> List[str]

Get files upload purpose options.

Purpose

Returns the files upload purpose options value used by the Gipity interface. The helper centralizes option lookup and fallback behavior for callers.

Parameters:

Name Type Description Default
files Files

Value supplied to the helper.

required

Returns:

Type Description
List[str]

Value produced by the get_files_upload_purpose_options helper according to its function

List[str]

annotation and return statements.

Source code in app.py
def get_files_upload_purpose_options( files: Files ) -> List[ str ]:
	"""Get files upload purpose options.

        Purpose:
            Returns the files upload purpose options value used by the Gipity interface. The helper
            centralizes option lookup and fallback behavior for callers.

        Args:
            files (Files): Value supplied to the helper.

        Returns:
            Value produced by the get_files_upload_purpose_options helper according to its function
            annotation and return statements.
    """
	options = getattr( files, 'upload_purpose_options', None )
	if isinstance( options, list ) and len( options ) > 0:
		return options
	options = getattr( files, 'purpose_options', None )
	if isinstance( options, list ) and len( options ) > 0:
		return options
	return [ 'assistants', 'batch', 'fine-tune', 'vision', 'user_data', 'evals' ]

get_files_filter_purpose_options

get_files_filter_purpose_options(files: Files) -> List[str]

Get files filter purpose options.

Purpose

Returns the files filter purpose options value used by the Gipity interface. The helper centralizes option lookup and fallback behavior for callers.

Parameters:

Name Type Description Default
files Files

Value supplied to the helper.

required

Returns:

Type Description
List[str]

Value produced by the get_files_filter_purpose_options helper according to its function

List[str]

annotation and return statements.

Source code in app.py
def get_files_filter_purpose_options( files: Files ) -> List[ str ]:
	"""Get files filter purpose options.

        Purpose:
            Returns the files filter purpose options value used by the Gipity interface. The helper
            centralizes option lookup and fallback behavior for callers.

        Args:
            files (Files): Value supplied to the helper.

        Returns:
            Value produced by the get_files_filter_purpose_options helper according to its function
            annotation and return statements.
    """
	options = getattr( files, 'file_purpose_options', None )
	if isinstance( options, list ) and len( options ) > 0:
		return [ '' ] + options
	return [ '', 'assistants', 'assistants_output', 'batch', 'batch_output', 'fine-tune',
	         'fine-tune-results', 'vision', 'user_data', 'evals' ]

get_files_model_options

get_files_model_options(files: Files) -> List[str]

Get files model options.

Purpose

Returns the files model options value used by the Gipity interface. The helper centralizes option lookup and fallback behavior for callers.

Parameters:

Name Type Description Default
files Files

Value supplied to the helper.

required

Returns:

Type Description
List[str]

Value produced by the get_files_model_options helper according to its function

List[str]

annotation and return statements.

Source code in app.py
def get_files_model_options( files: Files ) -> List[ str ]:
	"""Get files model options.

        Purpose:
            Returns the files model options value used by the Gipity interface. The helper
            centralizes option lookup and fallback behavior for callers.

        Args:
            files (Files): Value supplied to the helper.

        Returns:
            Value produced by the get_files_model_options helper according to its function
            annotation and return statements.
    """
	options = getattr( files, 'model_options', None )
	if isinstance( options, list ) and len( options ) > 0:
		return [ '' ] + options
	return [ '', 'gpt-5-mini', 'gpt-5-nano', 'gpt-4.1-mini', 'gpt-4.1-nano', 'gpt-4o-mini' ]

save_files_upload

save_files_upload(uploaded_file: Any) -> str | None

Save files upload.

Purpose

Saves the files upload value for later workflow use while preserving the caller-facing return contract.

Parameters:

Name Type Description Default
uploaded_file Any

Value supplied to the helper.

required

Returns:

Type Description
str | None

Value produced by the save_files_upload helper according to its function annotation and

str | None

return statements.

Source code in app.py
def save_files_upload( uploaded_file: Any ) -> str | None:
	"""Save files upload.

        Purpose:
            Saves the files upload value for later workflow use while preserving the caller-facing
            return contract.

        Args:
            uploaded_file (Any): Value supplied to the helper.

        Returns:
            Value produced by the save_files_upload helper according to its function annotation and
            return statements.
    """
	if uploaded_file is None:
		return None
	try:
		name = getattr( uploaded_file, 'name', '' )
		suffix = Path( name ).suffix if isinstance( name, str ) and name.strip( ) else ''
		if not suffix:
			suffix = '.tmp'
		with tempfile.NamedTemporaryFile( delete=False, suffix=suffix ) as tmp:
			if hasattr( uploaded_file, 'getbuffer' ):
				tmp.write( uploaded_file.getbuffer( ) )
			elif hasattr( uploaded_file, 'read' ):
				tmp.write( uploaded_file.read( ) )
			else:
				return None
			return tmp.name
	except Exception as e:
		exception = Error( e )
		exception.module = 'app'
		exception.cause = 'save_files_upload'
		exception.method = 'save_files_upload( ... )'
		Logger( ).write( exception )
		return None

normalize_files_table

normalize_files_table(rows: Any) -> List[Dict[str, Any]]

Normalize files table.

Purpose

Normalizes the files table input into the stable shape expected by downstream Gipity helpers and display logic.

Parameters:

Name Type Description Default
rows Any

Value supplied to the helper.

required

Returns:

Type Description
List[Dict[str, Any]]

Value produced by the normalize_files_table helper according to its function annotation

List[Dict[str, Any]]

and return statements.

Source code in app.py
def normalize_files_table( rows: Any ) -> List[ Dict[ str, Any ] ]:
	"""Normalize files table.

        Purpose:
            Normalizes the files table input into the stable shape expected by downstream Gipity
            helpers and display logic.

        Args:
            rows (Any): Value supplied to the helper.

        Returns:
            Value produced by the normalize_files_table helper according to its function annotation
            and return statements.
    """
	if rows is None:
		return [ ]
	if isinstance( rows, dict ) and isinstance( rows.get( 'data' ), list ):
		items = rows.get( 'data', [ ] )
	elif isinstance( rows, list ):
		items = rows
	else:
		items = getattr( rows, 'data', [ ] )
	normalized: List[ Dict[ str, Any ] ] = [ ]
	for item in items:
		if isinstance( item, dict ):
			source = item
		elif hasattr( item, 'model_dump' ):
			try:
				source = item.model_dump( )
			except Exception as e:
				exception = Error( e )
				exception.module = 'app'
				exception.cause = 'normalize_files_table'
				exception.method = 'normalize_files_table( ... )'
				Logger( ).write( exception )
				source = { }
		else:
			source = { 'id': getattr( item, 'id', None ),
			           'filename': getattr( item, 'filename', None ),
			           'purpose': getattr( item, 'purpose', None ),
			           'bytes': getattr( item, 'bytes', None ),
			           'created_at': getattr( item, 'created_at', None ),
			           'expires_at': getattr( item, 'expires_at', None ),
			           'status': getattr( item, 'status', None ),
			           'object': getattr( item, 'object', None ) }
		file_id = source.get( 'id' )
		if not file_id:
			continue
		normalized.append( { 'id': file_id, 'filename': source.get( 'filename', '' ),
		                     'purpose': source.get( 'purpose', '' ),
		                     'bytes': source.get( 'bytes', 0 ),
		                     'created_at': source.get( 'created_at', '' ),
		                     'expires_at': source.get( 'expires_at', '' ),
		                     'status': source.get( 'status', '' ),
		                     'object': source.get( 'object', '' ) } )
	return normalized

build_files_dataframe

build_files_dataframe(
    rows: List[Dict[str, Any]],
) -> pd.DataFrame

Build files dataframe.

Purpose

Builds the files dataframe value used by the Gipity interface or provider wrapper. The function normalizes inputs and returns a stable object for downstream use.

Parameters:

Name Type Description Default
rows List[Dict[str, Any]]

Value supplied to the helper.

required

Returns:

Type Description
DataFrame

Value produced by the build_files_dataframe helper according to its function annotation

DataFrame

and return statements.

Source code in app.py
def build_files_dataframe( rows: List[ Dict[ str, Any ] ] ) -> pd.DataFrame:
	"""Build files dataframe.

        Purpose:
            Builds the files dataframe value used by the Gipity interface or provider wrapper. The
            function normalizes inputs and returns a stable object for downstream use.

        Args:
            rows (List[Dict[str, Any]]): Value supplied to the helper.

        Returns:
            Value produced by the build_files_dataframe helper according to its function annotation
            and return statements.
    """
	if not isinstance( rows, list ) or len( rows ) == 0:
		return pd.DataFrame( )
	df_files = pd.DataFrame( rows )
	preferred = [ 'id', 'filename', 'purpose', 'bytes', 'created_at', 'expires_at', 'status',
	              'object' ]
	columns = [ column for column in preferred if column in df_files.columns ]
	extras = [ column for column in df_files.columns if column not in columns ]
	return df_files[ columns + extras ]

build_file_selection_options

build_file_selection_options(
    rows: List[Dict[str, Any]],
) -> Dict[str, str]

Build file selection options.

Purpose

Builds the file selection options value used by the Gipity interface or provider wrapper. The function normalizes inputs and returns a stable object for downstream use.

Parameters:

Name Type Description Default
rows List[Dict[str, Any]]

Value supplied to the helper.

required

Returns:

Type Description
Dict[str, str]

Value produced by the build_file_selection_options helper according to its function

Dict[str, str]

annotation and return statements.

Source code in app.py
def build_file_selection_options( rows: List[ Dict[ str, Any ] ] ) -> Dict[ str, str ]:
	"""Build file selection options.

        Purpose:
            Builds the file selection options value used by the Gipity interface or provider
            wrapper. The function normalizes inputs and returns a stable object for downstream use.

        Args:
            rows (List[Dict[str, Any]]): Value supplied to the helper.

        Returns:
            Value produced by the build_file_selection_options helper according to its function
            annotation and return statements.
    """
	options: Dict[ str, str ] = { }
	if not isinstance( rows, list ):
		return options
	for row in rows:
		if not isinstance( row, dict ):
			continue
		file_id = row.get( 'id' )
		if not isinstance( file_id, str ) or not file_id.strip( ):
			continue
		filename = row.get( 'filename' ) or 'Unnamed file'
		purpose = row.get( 'purpose' ) or 'unknown'
		label = f'{filename} — {file_id} — {purpose}'
		options[ label ] = file_id
	return options

get_selected_file_id

get_selected_file_id(
    selected_label: str | None,
    options: Dict[str, str] | None = None,
) -> str | None

Get selected file id.

Purpose

Returns the selected file id value used by the Gipity interface. The helper centralizes option lookup and fallback behavior for callers.

Parameters:

Name Type Description Default
selected_label str | None

Value supplied to the helper.

required
options Dict[str, str] | None

Value supplied to the helper.

None

Returns:

Type Description
str | None

Value produced by the get_selected_file_id helper according to its function annotation

str | None

and return statements.

Source code in app.py
def get_selected_file_id( selected_label: str | None,
		options: Dict[ str, str ] | None = None ) -> str | None:
	"""Get selected file id.

        Purpose:
            Returns the selected file id value used by the Gipity interface. The helper centralizes
            option lookup and fallback behavior for callers.

        Args:
            selected_label (str | None): Value supplied to the helper.
            options (Dict[str, str] | None): Value supplied to the helper.

        Returns:
            Value produced by the get_selected_file_id helper according to its function annotation
            and return statements.
    """
	if not isinstance( selected_label, str ) or not selected_label.strip( ):
		return None
	value = selected_label.strip( )
	if isinstance( options, dict ) and value in options:
		return options[ value ]
	if value.startswith( 'file-' ):
		return value
	return None

render_files_table

render_files_table(rows: List[Dict[str, Any]]) -> None

Render files table.

Purpose

Renders the files table user-interface section or display element in Streamlit while preserving the application state expected by the surrounding workflow.

Parameters:

Name Type Description Default
rows List[Dict[str, Any]]

Value supplied to the helper.

required
Source code in app.py
def render_files_table( rows: List[ Dict[ str, Any ] ] ) -> None:
	"""Render files table.

        Purpose:
            Renders the files table user-interface section or display element in Streamlit while
            preserving the application state expected by the surrounding workflow.

        Args:
            rows (List[Dict[str, Any]]): Value supplied to the helper.
    """
	df_files = build_files_dataframe( rows )
	st.session_state[ 'files_df' ] = df_files
	if df_files.empty:
		st.info( 'No files available.' )
		return
	st.data_editor( df_files, use_container_width=True, hide_index=True )

render_file_metadata

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

Render file metadata.

Purpose

Renders the file metadata user-interface section or display element in Streamlit while preserving the application state expected by the surrounding workflow.

Parameters:

Name Type Description Default
metadata Dict[str, Any] | None

Value supplied to the helper.

required
Source code in app.py
def render_file_metadata( metadata: Dict[ str, Any ] | None ) -> None:
	"""Render file metadata.

        Purpose:
            Renders the file metadata user-interface section or display element in Streamlit while
            preserving the application state expected by the surrounding workflow.

        Args:
            metadata (Dict[str, Any] | None): Value supplied to the helper.
    """
	if not isinstance( metadata, dict ) or len( metadata ) == 0:
		st.info( 'No file metadata available.' )
		return
	m1, m2, m3, m4 = st.columns( [ 0.25, 0.25, 0.25, 0.25 ], border=True, gap='xxsmall' )
	with m1:
		st.metric( 'Purpose', metadata.get( 'purpose', '—' ) or '—' )
	with m2:
		st.metric( 'Bytes', metadata.get( 'bytes', 0 ) or 0 )
	with m3:
		st.metric( 'Status', metadata.get( 'status', '—' ) or '—' )
	with m4:
		st.metric( 'Object', metadata.get( 'object', '—' ) or '—' )
	st.json( metadata )

render_file_content

render_file_content(
    content: str | bytes | Dict[str, Any] | None,
) -> None

Render file content.

Purpose

Renders the file content user-interface section or display element in Streamlit while preserving the application state expected by the surrounding workflow.

Parameters:

Name Type Description Default
content str | bytes | Dict[str, Any] | None

Value supplied to the helper.

required
Source code in app.py
def render_file_content( content: str | bytes | Dict[ str, Any ] | None ) -> None:
	"""Render file content.

        Purpose:
            Renders the file content user-interface section or display element in Streamlit while
            preserving the application state expected by the surrounding workflow.

        Args:
            content (str | bytes | Dict[str, Any] | None): Value supplied to the helper.
    """
	if content is None:
		st.info( 'No file content available.' )
		return
	if isinstance( content, bytes ):
		st.download_button( label='Download File Content', data=content,
			file_name='openai_file_content.bin', mime='application/octet-stream', width='stretch' )
		return
	if isinstance( content, dict ):
		st.json( content )
		return
	if isinstance( content, str ):
		if not content.strip( ):
			st.info( 'File content is empty.' )
			return
		st.text_area( label='File Content', value=content, height=300, width='stretch',
			disabled=True )
		return
	st.write( content )

render_file_delete_result

render_file_delete_result(
    result: Dict[str, Any] | None,
) -> None

Render file delete result.

Purpose

Renders the file delete result user-interface section or display element in Streamlit while preserving the application state expected by the surrounding workflow.

Parameters:

Name Type Description Default
result Dict[str, Any] | None

Value supplied to the helper.

required
Source code in app.py
def render_file_delete_result( result: Dict[ str, Any ] | None ) -> None:
	"""Render file delete result.

        Purpose:
            Renders the file delete result user-interface section or display element in Streamlit
            while preserving the application state expected by the surrounding workflow.

        Args:
            result (Dict[str, Any] | None): Value supplied to the helper.
    """
	if not isinstance( result, dict ) or len( result ) == 0:
		return
	deleted = result.get( 'deleted' )
	if deleted is True:
		st.success( f"Deleted file: {result.get( 'id', '' )}" )
	else:
		st.warning( 'Delete request completed, but deletion status was not confirmed.' )
	st.json( result )

clear_files_messages

clear_files_messages() -> None

Clear files messages.

Purpose

Clears the files messages state used by the current workflow so the user interface can start from a clean output state.

Source code in app.py
def clear_files_messages( ) -> None:
	"""Clear files messages.

        Purpose:
            Clears the files messages state used by the current workflow so the user interface can
            start from a clean output state.
    """
	st.session_state.files_messages = [ ]

clear_files_outputs

clear_files_outputs() -> None

Clear files outputs.

Purpose

Clears the files outputs state used by the current workflow so the user interface can start from a clean output state.

Source code in app.py
def clear_files_outputs( ) -> None:
	"""Clear files outputs.

        Purpose:
            Clears the files outputs state used by the current workflow so the user interface can
            start from a clean output state.
    """
	st.session_state[ 'files_metadata' ] = { }
	st.session_state[ 'files_content' ] = ''
	st.session_state[ 'files_content_bytes' ] = None
	st.session_state[ 'files_delete_result' ] = { }
	st.session_state[ 'files_last_answer' ] = ''

reset_files_controls

reset_files_controls() -> None

Reset files controls.

Purpose

Resets the files controls state used by the application. The function clears related Streamlit keys without performing provider calls.

Source code in app.py
def reset_files_controls( ) -> None:
	"""Reset files controls.

        Purpose:
            Resets the files controls state used by the application. The function clears related
            Streamlit keys without performing provider calls.
    """
	for key in [ 'files_model', 'files_purpose', 'files_filter_purpose', 'files_type', 'files_id',
	             'files_url' ]:
		if key in st.session_state:
			del st.session_state[ key ]

reset_files_all

reset_files_all() -> None

Reset files all.

Purpose

Resets the files all state used by the application. The function clears related Streamlit keys without performing provider calls.

Source code in app.py
def reset_files_all( ) -> None:
	"""Reset files all.

        Purpose:
            Resets the files all state used by the application. The function clears related
            Streamlit keys without performing provider calls.
    """
	reset_files_controls( )
	clear_files_outputs( )
	st.session_state[ 'files_table' ] = [ ]
	st.session_state[ 'files_df' ] = pd.DataFrame( )
	st.session_state.files_messages = [ ]

clear_files_instructions

clear_files_instructions() -> None

Clear files instructions.

Purpose

Clears the files instructions state used by the current workflow so the user interface can start from a clean output state.

Source code in app.py
def clear_files_instructions( ) -> None:
	"""Clear files instructions.

        Purpose:
            Clears the files instructions state used by the current workflow so the user interface
            can start from a clean output state.
    """
	st.session_state[ 'files_system_instructions' ] = ''
	st.session_state[ 'instructions' ] = ''

load_files_instruction_template

load_files_instruction_template() -> None

Load files instruction template.

Purpose

Loads the files instruction template resource or state required by the Gipity workflow and returns the prepared value for caller use.

Source code in app.py
def load_files_instruction_template( ) -> None:
	"""Load files instruction template.

        Purpose:
            Loads the files instruction template resource or state required by the Gipity workflow
            and returns the prepared value for caller use.
    """
	name = st.session_state.get( 'instructions' )
	if name and name != 'No Templates Found':
		text = fetch_prompt_text( cfg.DB_PATH, name )
		if text is not None:
			st.session_state[ 'files_system_instructions' ] = text

convert_files_system_instructions

convert_files_system_instructions() -> None

Convert files system instructions.

Purpose

Provides the convert files system instructions helper used by the Gipity Streamlit application. The function supports UI state management, provider coordination, data normalization, or display behavior required by the surrounding workflow.

Source code in app.py
def convert_files_system_instructions( ) -> None:
	"""Convert files system instructions.

        Purpose:
            Provides the convert files system instructions helper used by the Gipity Streamlit
            application. The function supports UI state management, provider coordination, data
            normalization, or display behavior required by the surrounding workflow.
    """
	text = st.session_state.get( 'files_system_instructions', '' )
	if not isinstance( text, str ) or not text.strip( ):
		return
	source = text.strip( )
	if cfg.XML_BLOCK_PATTERN.search( source ):
		converted = convert_xml( source )
	else:
		converted = convert_markdown( source )
	st.session_state[ 'files_system_instructions' ] = converted

run_files_upload

run_files_upload(
    files: Files, uploaded_file: Any, purpose: str | None
) -> Dict[str, Any]

Run files upload.

Purpose

Runs the files upload workflow from the Streamlit interface by validating current inputs, calling the appropriate wrapper or helper, and storing relevant output state.

Parameters:

Name Type Description Default
files Files

Value supplied to the helper.

required
uploaded_file Any

Value supplied to the helper.

required
purpose str | None

Value supplied to the helper.

required

Returns:

Type Description
Dict[str, Any]

Value produced by the run_files_upload helper according to its function annotation and

Dict[str, Any]

return statements.

Source code in app.py
def run_files_upload( files: Files, uploaded_file: Any, purpose: str | None ) -> Dict[ str, Any ]:
	"""Run files upload.

        Purpose:
            Runs the files upload workflow from the Streamlit interface by validating current
            inputs, calling the appropriate wrapper or helper, and storing relevant output state.

        Args:
            files (Files): Value supplied to the helper.
            uploaded_file (Any): Value supplied to the helper.
            purpose (str | None): Value supplied to the helper.

        Returns:
            Value produced by the run_files_upload helper according to its function annotation and
            return statements.
    """
	if uploaded_file is None:
		st.warning( 'Select a file before uploading.' )
		return { }
	filepath = save_files_upload( uploaded_file )
	if not filepath:
		st.warning( 'The uploaded file could not be saved locally.' )
		return { }
	try:
		metadata = files.upload( filepath=filepath, purpose=purpose or 'user_data' )
		metadata = metadata if isinstance( metadata, dict ) else { }
		if metadata.get( 'id' ):
			st.session_state[ 'files_id' ] = metadata.get( 'id' )
			st.session_state[ 'files_metadata' ] = metadata
		return metadata
	finally:
		try:
			if os.path.exists( filepath ):
				os.remove( filepath )
		except Exception as e:
			exception = Error( e )
			exception.module = 'app'
			exception.cause = 'run_files_upload'
			exception.method = 'run_files_upload( ... )'
			Logger( ).write( exception )
			pass

run_files_list

run_files_list(
    files: Files, purpose: str | None = None
) -> List[Dict[str, Any]]

Run files list.

Purpose

Runs the files list workflow from the Streamlit interface by validating current inputs, calling the appropriate wrapper or helper, and storing relevant output state.

Parameters:

Name Type Description Default
files Files

Value supplied to the helper.

required
purpose str | None

Value supplied to the helper.

None

Returns:

Type Description
List[Dict[str, Any]]

Value produced by the run_files_list helper according to its function annotation and

List[Dict[str, Any]]

return statements.

Source code in app.py
def run_files_list( files: Files, purpose: str | None = None ) -> List[ Dict[ str, Any ] ]:
	"""Run files list.

        Purpose:
            Runs the files list workflow from the Streamlit interface by validating current inputs,
            calling the appropriate wrapper or helper, and storing relevant output state.

        Args:
            files (Files): Value supplied to the helper.
            purpose (str | None): Value supplied to the helper.

        Returns:
            Value produced by the run_files_list helper according to its function annotation and
            return statements.
    """
	rows = files.list(
		purpose=purpose if isinstance( purpose, str ) and purpose.strip( ) else None )
	rows = normalize_files_table( rows )
	st.session_state[ 'files_table' ] = rows
	st.session_state[ 'files_df' ] = build_files_dataframe( rows )
	return rows

run_files_retrieve

run_files_retrieve(
    files: Files, file_id: str | None
) -> Dict[str, Any]

Run files retrieve.

Purpose

Runs the files retrieve workflow from the Streamlit interface by validating current inputs, calling the appropriate wrapper or helper, and storing relevant output state.

Parameters:

Name Type Description Default
files Files

Value supplied to the helper.

required
file_id str | None

Value supplied to the helper.

required

Returns:

Type Description
Dict[str, Any]

Value produced by the run_files_retrieve helper according to its function annotation and

Dict[str, Any]

return statements.

Source code in app.py
def run_files_retrieve( files: Files, file_id: str | None ) -> Dict[ str, Any ]:
	"""Run files retrieve.

        Purpose:
            Runs the files retrieve workflow from the Streamlit interface by validating current
            inputs, calling the appropriate wrapper or helper, and storing relevant output state.

        Args:
            files (Files): Value supplied to the helper.
            file_id (str | None): Value supplied to the helper.

        Returns:
            Value produced by the run_files_retrieve helper according to its function annotation and
            return statements.
    """
	if not isinstance( file_id, str ) or not file_id.strip( ):
		st.warning( 'Select or enter a file ID before retrieving metadata.' )
		return { }
	metadata = files.retrieve( id=file_id.strip( ) )
	metadata = metadata if isinstance( metadata, dict ) else { }
	st.session_state[ 'files_metadata' ] = metadata
	return metadata

run_files_extract

run_files_extract(
    files: Files, file_id: str | None
) -> str | bytes | Dict[str, Any] | None

Run files extract.

Purpose

Retrieves downloadable content for a selected OpenAI file when the file purpose supports content retrieval. Input files intended for model or Vector Store use are identified before the content endpoint is called so unsupported requests do not reach the provider.

Parameters:

Name Type Description Default
files Files

OpenAI Files API wrapper.

required
file_id str | None

Selected OpenAI file identifier.

required

Returns:

Type Description
str | bytes | Dict[str, Any] | None

str | bytes | Dict[ str, Any ] | None: Retrieved file content when supported, otherwise no

str | bytes | Dict[str, Any] | None

value.

Source code in app.py
def run_files_extract( files: Files, file_id: str | None ) -> str | bytes | Dict[ str, Any ] | None:
	"""Run files extract.

	Purpose:
		Retrieves downloadable content for a selected OpenAI file when the file purpose supports
		content retrieval. Input files intended for model or Vector Store use are identified before
		the content endpoint is called so unsupported requests do not reach the provider.

	Args:
		files (Files): OpenAI Files API wrapper.
		file_id (str | None): Selected OpenAI file identifier.

	Returns:
		str | bytes | Dict[ str, Any ] | None: Retrieved file content when supported, otherwise no
		value.
	"""
	if not isinstance( file_id, str ) or not file_id.strip( ):
		st.warning( 'Select or enter a file ID before retrieving content.' )
		return None

	selected_id = file_id.strip( )
	metadata = files.retrieve( id=selected_id )
	metadata = metadata if isinstance( metadata, dict ) else { }

	purpose = str( metadata.get( 'purpose', '' ) or '' ).strip( )

	downloadable_purposes = { 'assistants_output', 'batch_output', 'fine-tune-results', }

	if purpose not in downloadable_purposes:
		st.session_state[ 'files_content' ] = ''
		st.session_state[ 'files_content_bytes' ] = None

		st.info( f'The selected file has purpose "{purpose or "unknown"}". '
		         'OpenAI does not expose this input file through the Files content-download '
		         'operation. '
		         'Use the file ID in a model request or attach the file to a Vector Store '
		         'instead.' )

		return None

	content = files.extract( id=selected_id )

	if isinstance( content, bytes ):
		st.session_state[ 'files_content_bytes' ] = content
		st.session_state[ 'files_content' ] = ''
	elif isinstance( content, str ):
		st.session_state[ 'files_content' ] = content
		st.session_state[ 'files_content_bytes' ] = None
	elif isinstance( content, dict ):
		st.session_state[ 'files_content' ] = str( content )
		st.session_state[ 'files_content_bytes' ] = None
	else:
		st.session_state[ 'files_content' ] = ''
		st.session_state[ 'files_content_bytes' ] = None

	return content

run_files_delete

run_files_delete(
    files: Files, file_id: str | None
) -> Dict[str, Any]

Run files delete.

Purpose

Runs the files delete workflow from the Streamlit interface by validating current inputs, calling the appropriate wrapper or helper, and storing relevant output state.

Parameters:

Name Type Description Default
files Files

Value supplied to the helper.

required
file_id str | None

Value supplied to the helper.

required

Returns:

Type Description
Dict[str, Any]

Value produced by the run_files_delete helper according to its function annotation and

Dict[str, Any]

return statements.

Source code in app.py
def run_files_delete( files: Files, file_id: str | None ) -> Dict[ str, Any ]:
	"""Run files delete.

        Purpose:
            Runs the files delete workflow from the Streamlit interface by validating current
            inputs, calling the appropriate wrapper or helper, and storing relevant output state.

        Args:
            files (Files): Value supplied to the helper.
            file_id (str | None): Value supplied to the helper.

        Returns:
            Value produced by the run_files_delete helper according to its function annotation and
            return statements.
    """
	if not isinstance( file_id, str ) or not file_id.strip( ):
		st.warning( 'Select or enter a file ID before deleting a file.' )
		return { }
	result = files.delete( id=file_id.strip( ) )
	result = result if isinstance( result, dict ) else { }
	st.session_state[ 'files_delete_result' ] = result
	if result.get( 'deleted' ) is True:
		st.session_state[ 'files_id' ] = ''
	return result

run_files_analysis

run_files_analysis(
    files: Files,
    file_id: str | None,
    prompt: str | None,
    model: str | None = None,
) -> str | None

Run files analysis.

Purpose

Runs the files analysis workflow from the Streamlit interface by validating current inputs, calling the appropriate wrapper or helper, and storing relevant output state.

Parameters:

Name Type Description Default
files Files

Value supplied to the helper.

required
file_id str | None

Value supplied to the helper.

required
prompt str | None

Value supplied to the helper.

required
model str | None

Value supplied to the helper.

None

Returns:

Type Description
str | None

Value produced by the run_files_analysis helper according to its function annotation and

str | None

return statements.

Source code in app.py
def run_files_analysis( files: Files, file_id: str | None, prompt: str | None,
		model: str | None = None ) -> str | None:
	"""Run files analysis.

        Purpose:
            Runs the files analysis workflow from the Streamlit interface by validating current
            inputs, calling the appropriate wrapper or helper, and storing relevant output state.

        Args:
            files (Files): Value supplied to the helper.
            file_id (str | None): Value supplied to the helper.
            prompt (str | None): Value supplied to the helper.
            model (str | None): Value supplied to the helper.

        Returns:
            Value produced by the run_files_analysis helper according to its function annotation and
            return statements.
    """
	if not isinstance( file_id, str ) or not file_id.strip( ):
		st.warning( 'Select or enter a file ID before analyzing a file.' )
		return None
	if not isinstance( prompt, str ) or not prompt.strip( ):
		st.warning( 'Enter a prompt before analyzing a file.' )
		return None
	model_value = model if isinstance( model, str ) and model.strip( ) else 'gpt-4o-mini'
	response = files.search( id=file_id.strip( ), query=prompt.strip( ), model=model_value )
	if isinstance( response, str ) and response.strip( ):
		st.session_state[ 'files_last_answer' ] = response.strip( )
		return response.strip( )
	return response

resolve_files_current_id

resolve_files_current_id() -> str

Resolve current Files API file identifier.

Purpose

Resolves the active OpenAI file identifier using the Files mode's established precedence: a selected listed file, a manually entered file identifier, and finally the persisted file identifier created by upload or prior selection.

Returns:

Name Type Description
str str

Resolved OpenAI file identifier or an empty string when no file is available.

Source code in app.py
def resolve_files_current_id( ) -> str:
	"""Resolve current Files API file identifier.

	Purpose:
		Resolves the active OpenAI file identifier using the Files mode's established precedence:
		a selected listed file, a manually entered file identifier, and finally the persisted file
		identifier created by upload or prior selection.

	Returns:
		str: Resolved OpenAI file identifier or an empty string when no file is available.
	"""
	rows = st.session_state.get( 'files_table', [ ] )
	options = build_file_selection_options( rows if isinstance( rows, list ) else [ ] )
	selected_label = st.session_state.get( 'files_selected_label', '' )
	selected_id = get_selected_file_id( selected_label=selected_label,
		options=options )

	if isinstance( selected_id, str ) and selected_id.strip( ):
		return selected_id.strip( )

	manual_id = st.session_state.get( 'files_manual_id', '' )
	if isinstance( manual_id, str ) and manual_id.strip( ):
		return manual_id.strip( )

	persisted_id = st.session_state.get( 'files_id', '' )
	if isinstance( persisted_id, str ) and persisted_id.strip( ):
		return persisted_id.strip( )

	return ''

get_configured_vector_store_names

get_configured_vector_store_names() -> List[str]

Get configured vector store names.

Purpose

Returns the configured OpenAI Vector Store display names in their declared order.

Returns:

Type Description
List[str]

List[ str ]: Configured Vector Store display names.

Source code in app.py
def get_configured_vector_store_names( ) -> List[ str ]:
	"""Get configured vector store names.

	Purpose:
		Returns the configured OpenAI Vector Store display names in their declared order.

	Returns:
		List[ str ]: Configured Vector Store display names.
	"""
	stores = getattr( cfg, 'GPT_VECTOR_STORES', { } )
	return list( stores.keys( ) ) if isinstance( stores, dict ) else [ ]

get_vector_store_ids

get_vector_store_ids(names: List[str] | None) -> List[str]

Get vector store IDs.

Purpose

Resolves configured Vector Store display names into OpenAI Vector Store identifiers.

Parameters:

Name Type Description Default
names List[str] | None

Selected configured Vector Store names.

required

Returns:

Type Description
List[str]

List[ str ]: Resolved OpenAI Vector Store identifiers.

Source code in app.py
def get_vector_store_ids( names: List[ str ] | None ) -> List[ str ]:
	"""Get vector store IDs.

	Purpose:
		Resolves configured Vector Store display names into OpenAI Vector Store identifiers.

	Args:
		names (List[ str ] | None): Selected configured Vector Store names.

	Returns:
		List[ str ]: Resolved OpenAI Vector Store identifiers.
	"""
	stores = getattr( cfg, 'GPT_VECTOR_STORES', { } )
	if not isinstance( stores, dict ) or not isinstance( names, list ):
		return [ ]

	return [ str( stores[ name ] ).strip( ) for name in names if
		name in stores and str( stores[ name ] ).strip( ) ]

get_vector_store_id

get_vector_store_id(name: str | None) -> str

Get vector store ID.

Purpose

Resolves one configured Vector Store display name into its OpenAI Vector Store identifier.

Parameters:

Name Type Description Default
name str | None

Selected configured Vector Store name.

required

Returns:

Name Type Description
str str

Resolved OpenAI Vector Store identifier or an empty string.

Source code in app.py
def get_vector_store_id( name: str | None ) -> str:
	"""Get vector store ID.

	Purpose:
		Resolves one configured Vector Store display name into its OpenAI Vector Store identifier.

	Args:
		name (str | None): Selected configured Vector Store name.

	Returns:
		str: Resolved OpenAI Vector Store identifier or an empty string.
	"""
	stores = getattr( cfg, 'GPT_VECTOR_STORES', { } )
	if not isinstance( stores, dict ):
		return ''

	if not isinstance( name, str ) or not name.strip( ):
		return ''

	return str( stores.get( name.strip( ), '' ) or '' ).strip( )

ensure_vectorstores_mode_state

ensure_vectorstores_mode_state() -> None

Ensure vectorstores mode state.

Purpose

Ensures the required vectorstores mode state session-state keys or runtime resources exist before the related interface controls are rendered.

Source code in app.py
def ensure_vectorstores_mode_state( ) -> None:
	"""Ensure vectorstores mode state.

        Purpose:
            Ensures the required vectorstores mode state session-state keys or runtime resources
            exist before the related interface controls are rendered.
    """
	if 'stores_model' not in st.session_state:
		st.session_state[ 'stores_model' ] = ''
	if 'stores_id' not in st.session_state:
		st.session_state[ 'stores_id' ] = ''
	if 'stores_manual_id' not in st.session_state:
		st.session_state[ 'stores_manual_id' ] = ''
	if 'stores_selected_label' not in st.session_state:
		st.session_state[ 'stores_selected_label' ] = ''
	if 'stores_name' not in st.session_state:
		st.session_state[ 'stores_name' ] = ''
	if 'stores_description' not in st.session_state:
		st.session_state[ 'stores_description' ] = ''
	if 'stores_metadata' not in st.session_state:
		st.session_state[ 'stores_metadata' ] = ''
	if 'stores_expires_days' not in st.session_state:
		st.session_state[ 'stores_expires_days' ] = 0
	if 'stores_expires_anchor' not in st.session_state:
		st.session_state[ 'stores_expires_anchor' ] = 'last_active_at'
	if 'stores_file_ids' not in st.session_state:
		st.session_state[ 'stores_file_ids' ] = ''
	if 'stores_chunking_strategy' not in st.session_state:
		st.session_state[ 'stores_chunking_strategy' ] = 'auto'
	if 'stores_chunk_size' not in st.session_state:
		st.session_state[ 'stores_chunk_size' ] = 800
	if 'stores_chunk_overlap' not in st.session_state:
		st.session_state[ 'stores_chunk_overlap' ] = 400
	if 'stores_table' not in st.session_state:
		st.session_state[ 'stores_table' ] = [ ]
	if 'stores_df' not in st.session_state:
		st.session_state[ 'stores_df' ] = pd.DataFrame( )
	if 'stores_store_metadata' not in st.session_state:
		st.session_state[ 'stores_store_metadata' ] = { }
	if 'stores_files_table' not in st.session_state:
		st.session_state[ 'stores_files_table' ] = [ ]
	if 'stores_files_df' not in st.session_state:
		st.session_state[ 'stores_files_df' ] = pd.DataFrame( )
	if 'stores_file_id' not in st.session_state:
		st.session_state[ 'stores_file_id' ] = ''
	if 'stores_file_selected_label' not in st.session_state:
		st.session_state[ 'stores_file_selected_label' ] = ''
	if 'stores_file_attributes' not in st.session_state:
		st.session_state[ 'stores_file_attributes' ] = ''
	if 'stores_batch_id' not in st.session_state:
		st.session_state[ 'stores_batch_id' ] = ''
	if 'stores_batch_result' not in st.session_state:
		st.session_state[ 'stores_batch_result' ] = { }
	if 'stores_search_query' not in st.session_state:
		st.session_state[ 'stores_search_query' ] = ''
	if 'stores_search_results' not in st.session_state:
		st.session_state[ 'stores_search_results' ] = [ ]
	if 'stores_max_results' not in st.session_state:
		st.session_state[ 'stores_max_results' ] = 10
	if 'stores_ranker' not in st.session_state:
		st.session_state[ 'stores_ranker' ] = 'auto'
	if 'stores_score_threshold' not in st.session_state:
		st.session_state[ 'stores_score_threshold' ] = 0.0
	if 'stores_rewrite_query' not in st.session_state:
		st.session_state[ 'stores_rewrite_query' ] = False
	if 'stores_last_answer' not in st.session_state:
		st.session_state[ 'stores_last_answer' ] = ''
	if 'stores_system_instructions' not in st.session_state:
		st.session_state[ 'stores_system_instructions' ] = ''
	if 'stores_messages' not in st.session_state:
		st.session_state.stores_messages = [ ]
	if not isinstance( st.session_state.get( 'stores_messages' ), list ):
		st.session_state.stores_messages = [ ]

get_vector_store_model_options

get_vector_store_model_options(
    vector: VectorStores,
) -> List[str]

Get vector store model options.

Purpose

Returns the vector store model options value used by the Gipity interface. The helper centralizes option lookup and fallback behavior for callers.

Parameters:

Name Type Description Default
vector VectorStores

Value supplied to the helper.

required

Returns:

Type Description
List[str]

Value produced by the get_vector_store_model_options helper according to its function

List[str]

annotation and return statements.

Source code in app.py
def get_vector_store_model_options( vector: VectorStores ) -> List[ str ]:
	"""Get vector store model options.

        Purpose:
            Returns the vector store model options value used by the Gipity interface. The helper
            centralizes option lookup and fallback behavior for callers.

        Args:
            vector (VectorStores): Value supplied to the helper.

        Returns:
            Value produced by the get_vector_store_model_options helper according to its function
            annotation and return statements.
    """
	options = getattr( vector, 'model_options', None )
	if isinstance( options, list ) and len( options ) > 0:
		return [ '' ] + options
	return [ '', 'gpt-5-mini', 'gpt-5-nano', 'gpt-4.1-mini', 'gpt-4.1-nano', 'gpt-4o-mini' ]

get_vector_store_ranker_options

get_vector_store_ranker_options(
    vector: VectorStores,
) -> List[str]

Get vector store ranker options.

Purpose

Returns the vector store ranker options value used by the Gipity interface. The helper centralizes option lookup and fallback behavior for callers.

Parameters:

Name Type Description Default
vector VectorStores

Value supplied to the helper.

required

Returns:

Type Description
List[str]

Value produced by the get_vector_store_ranker_options helper according to its function

List[str]

annotation and return statements.

Source code in app.py
def get_vector_store_ranker_options( vector: VectorStores ) -> List[ str ]:
	"""Get vector store ranker options.

        Purpose:
            Returns the vector store ranker options value used by the Gipity interface. The helper
            centralizes option lookup and fallback behavior for callers.

        Args:
            vector (VectorStores): Value supplied to the helper.

        Returns:
            Value produced by the get_vector_store_ranker_options helper according to its function
            annotation and return statements.
    """
	options = getattr( vector, 'ranker_options', None )
	if isinstance( options, list ) and len( options ) > 0:
		return options
	return [ 'auto', 'default-2024-11-15' ]

get_vector_store_chunking_options

get_vector_store_chunking_options(
    vector: VectorStores,
) -> List[str]

Get vector store chunking options.

Purpose

Returns the vector store chunking options value used by the Gipity interface. The helper centralizes option lookup and fallback behavior for callers.

Parameters:

Name Type Description Default
vector VectorStores

Value supplied to the helper.

required

Returns:

Type Description
List[str]

Value produced by the get_vector_store_chunking_options helper according to its function

List[str]

annotation and return statements.

Source code in app.py
def get_vector_store_chunking_options( vector: VectorStores ) -> List[ str ]:
	"""Get vector store chunking options.

        Purpose:
            Returns the vector store chunking options value used by the Gipity interface. The helper
            centralizes option lookup and fallback behavior for callers.

        Args:
            vector (VectorStores): Value supplied to the helper.

        Returns:
            Value produced by the get_vector_store_chunking_options helper according to its function
            annotation and return statements.
    """
	options = getattr( vector, 'chunking_strategy_options', None )
	if isinstance( options, list ) and len( options ) > 0:
		return options
	return [ 'auto', 'static' ]

parse_vector_store_file_ids

parse_vector_store_file_ids(
    value: str | List[str] | None,
) -> List[str]

Parse vector store file ids.

Purpose

Provides the parse vector store file ids helper used by the Gipity Streamlit application. The function supports UI state management, provider coordination, data normalization, or display behavior required by the surrounding workflow.

Parameters:

Name Type Description Default
value str | List[str] | None

Value supplied to the helper.

required

Returns:

Type Description
List[str]

Value produced by the parse_vector_store_file_ids helper according to its function

List[str]

annotation and return statements.

Source code in app.py
def parse_vector_store_file_ids( value: str | List[ str ] | None ) -> List[ str ]:
	"""Parse vector store file ids.

        Purpose:
            Provides the parse vector store file ids helper used by the Gipity Streamlit
            application. The function supports UI state management, provider coordination, data
            normalization, or display behavior required by the surrounding workflow.

        Args:
            value (str | List[str] | None): Value supplied to the helper.

        Returns:
            Value produced by the parse_vector_store_file_ids helper according to its function
            annotation and return statements.
    """
	if value is None:
		return [ ]
	if isinstance( value, list ):
		return [ str( item ).strip( ) for item in value if str( item ).strip( ) ]
	if not isinstance( value, str ) or not value.strip( ):
		return [ ]
	return [ item.strip( ) for item in value.split( ',' ) if item.strip( ) ]

parse_vector_store_json

parse_vector_store_json(
    value: str | None, label: str = "JSON"
) -> Dict[str, Any]

Parse vector store json.

Purpose

Provides the parse vector store json helper used by the Gipity Streamlit application. The function supports UI state management, provider coordination, data normalization, or display behavior required by the surrounding workflow.

Parameters:

Name Type Description Default
value str | None

Value supplied to the helper.

required
label str

Value supplied to the helper.

'JSON'

Returns:

Type Description
Dict[str, Any]

Value produced by the parse_vector_store_json helper according to its function

Dict[str, Any]

annotation and return statements.

Source code in app.py
def parse_vector_store_json( value: str | None, label: str = 'JSON' ) -> Dict[ str, Any ]:
	"""Parse vector store json.

        Purpose:
            Provides the parse vector store json helper used by the Gipity Streamlit application.
            The function supports UI state management, provider coordination, data normalization, or
            display behavior required by the surrounding workflow.

        Args:
            value (str | None): Value supplied to the helper.
            label (str): Value supplied to the helper.

        Returns:
            Value produced by the parse_vector_store_json helper according to its function
            annotation and return statements.
    """
	if not isinstance( value, str ) or not value.strip( ):
		return { }
	try:
		parsed = json.loads( value )
	except Exception as exc:
		exception = Error( exc )
		exception.module = 'app'
		exception.cause = 'parse_vector_store_json'
		exception.method = 'parse_vector_store_json( ... )'
		Logger( ).write( exception )
		st.warning( f'{label} could not be parsed and will be omitted: {exc}' )
		return { }
	if not isinstance( parsed, dict ):
		st.warning( f'{label} must be a JSON object. It will be omitted.' )
		return { }
	return parsed

build_vector_store_expires_after_from_state

build_vector_store_expires_after_from_state(
    vector: VectorStores,
) -> Dict[str, Any] | None

Build vector store expires after from state.

Purpose

Builds the vector store expires after from state value used by the Gipity interface or provider wrapper. The function normalizes inputs and returns a stable object for downstream use.

Parameters:

Name Type Description Default
vector VectorStores

Value supplied to the helper.

required

Returns:

Type Description
Dict[str, Any] | None

Value produced by the build_vector_store_expires_after_from_state helper according to

Dict[str, Any] | None

its function annotation and return statements.

Source code in app.py
def build_vector_store_expires_after_from_state( vector: VectorStores ) -> Dict[ str, Any ] | None:
	"""Build vector store expires after from state.

        Purpose:
            Builds the vector store expires after from state value used by the Gipity interface or
            provider wrapper. The function normalizes inputs and returns a stable object for
            downstream use.

        Args:
            vector (VectorStores): Value supplied to the helper.

        Returns:
            Value produced by the build_vector_store_expires_after_from_state helper according to
            its function annotation and return statements.
    """
	days = st.session_state.get( 'stores_expires_days', 0 )
	anchor = st.session_state.get( 'stores_expires_anchor', 'last_active_at' )
	try:
		day_value = int( days )
	except Exception as e:
		exception = Error( e )
		exception.module = 'app'
		exception.cause = 'build_vector_store_expires_after_from_state'
		exception.method = 'build_vector_store_expires_after_from_state( ... )'
		Logger( ).write( exception )
		day_value = 0
	if day_value <= 0:
		return None
	return vector.build_expires_after( anchor=anchor, days=day_value )

build_vector_store_chunking_strategy_from_state

build_vector_store_chunking_strategy_from_state(
    vector: VectorStores,
) -> Dict[str, Any] | None

Build vector store chunking strategy from state.

Purpose

Builds the vector store chunking strategy from state value used by the Gipity interface or provider wrapper. The function normalizes inputs and returns a stable object for downstream use.

Parameters:

Name Type Description Default
vector VectorStores

Value supplied to the helper.

required

Returns:

Type Description
Dict[str, Any] | None

Value produced by the build_vector_store_chunking_strategy_from_state helper according

Dict[str, Any] | None

to its function annotation and return statements.

Source code in app.py
def build_vector_store_chunking_strategy_from_state( vector: VectorStores ) -> Dict[ str, Any ] | None:
	"""Build vector store chunking strategy from state.

        Purpose:
            Builds the vector store chunking strategy from state value used by the Gipity interface
            or provider wrapper. The function normalizes inputs and returns a stable object for
            downstream use.

        Args:
            vector (VectorStores): Value supplied to the helper.

        Returns:
            Value produced by the build_vector_store_chunking_strategy_from_state helper according
            to its function annotation and return statements.
    """
	strategy = st.session_state.get( 'stores_chunking_strategy', 'auto' )
	if not isinstance( strategy, str ) or not strategy.strip( ):
		return None
	if strategy == 'auto':
		return vector.build_chunking_strategy( strategy='auto' )
	return vector.build_chunking_strategy( strategy='static',
		max_chunk_size_tokens=st.session_state.get( 'stores_chunk_size', 800 ),
		chunk_overlap_tokens=st.session_state.get( 'stores_chunk_overlap', 400 ) )

build_vector_store_ranking_options_from_state

build_vector_store_ranking_options_from_state() -> (
    Dict[str, Any]
)

Build vector store ranking options from state.

Purpose

Builds the vector store ranking options from state value used by the Gipity interface or provider wrapper. The function normalizes inputs and returns a stable object for downstream use.

Returns:

Type Description
Dict[str, Any]

Value produced by the build_vector_store_ranking_options_from_state helper according to

Dict[str, Any]

its function annotation and return statements.

Source code in app.py
def build_vector_store_ranking_options_from_state( ) -> Dict[ str, Any ]:
	"""Build vector store ranking options from state.

        Purpose:
            Builds the vector store ranking options from state value used by the Gipity interface or
            provider wrapper. The function normalizes inputs and returns a stable object for
            downstream use.

        Returns:
            Value produced by the build_vector_store_ranking_options_from_state helper according to
            its function annotation and return statements.
    """
	ranker = st.session_state.get( 'stores_ranker', 'auto' )
	score_threshold = st.session_state.get( 'stores_score_threshold', 0.0 )
	options: Dict[ str, Any ] = { }
	if isinstance( ranker, str ) and ranker.strip( ):
		options[ 'ranker' ] = ranker.strip( )
	try:
		threshold = float( score_threshold )
	except Exception as e:
		exception = Error( e )
		exception.module = 'app'
		exception.cause = 'build_vector_store_ranking_options_from_state'
		exception.method = 'build_vector_store_ranking_options_from_state( ... )'
		Logger( ).write( exception )
		threshold = 0.0
	if threshold > 0.0:
		options[ 'score_threshold' ] = threshold
	return options

normalize_vector_store_rows

normalize_vector_store_rows(
    rows: Any,
) -> List[Dict[str, Any]]

Normalize vector store rows.

Purpose

Normalizes the vector store rows input into the stable shape expected by downstream Gipity helpers and display logic.

Parameters:

Name Type Description Default
rows Any

Value supplied to the helper.

required

Returns:

Type Description
List[Dict[str, Any]]

Value produced by the normalize_vector_store_rows helper according to its function

List[Dict[str, Any]]

annotation and return statements.

Source code in app.py
def normalize_vector_store_rows( rows: Any ) -> List[ Dict[ str, Any ] ]:
	"""Normalize vector store rows.

        Purpose:
            Normalizes the vector store rows input into the stable shape expected by downstream
            Gipity helpers and display logic.

        Args:
            rows (Any): Value supplied to the helper.

        Returns:
            Value produced by the normalize_vector_store_rows helper according to its function
            annotation and return statements.
    """
	if rows is None:
		return [ ]
	if isinstance( rows, dict ) and isinstance( rows.get( 'data' ), list ):
		items = rows.get( 'data', [ ] )
	elif isinstance( rows, list ):
		items = rows
	else:
		items = getattr( rows, 'data', [ ] )
	normalized: List[ Dict[ str, Any ] ] = [ ]
	for item in items:
		if isinstance( item, dict ):
			source = item
		elif hasattr( item, 'model_dump' ):
			try:
				source = item.model_dump( )
			except Exception as e:
				exception = Error( e )
				exception.module = 'app'
				exception.cause = 'normalize_vector_store_rows'
				exception.method = 'normalize_vector_store_rows( ... )'
				Logger( ).write( exception )
				source = { }
		else:
			source = { 'id': getattr( item, 'id', None ), 'name': getattr( item, 'name', None ),
			           'description': getattr( item, 'description', None ),
			           'created_at': getattr( item, 'created_at', None ),
			           'object': getattr( item, 'object', None ),
			           'usage_bytes': getattr( item, 'usage_bytes', None ),
			           'file_counts': getattr( item, 'file_counts', None ),
			           'status': getattr( item, 'status', None ),
			           'expires_at': getattr( item, 'expires_at', None ),
			           'last_active_at': getattr( item, 'last_active_at', None ) }
		store_id = source.get( 'id' )
		if not store_id:
			continue
		normalized.append( { 'id': store_id, 'name': source.get( 'name', '' ),
		                     'description': source.get( 'description', '' ),
		                     'status': source.get( 'status', '' ),
		                     'usage_bytes': source.get( 'usage_bytes', 0 ),
		                     'file_counts': source.get( 'file_counts', { } ),
		                     'created_at': source.get( 'created_at', '' ),
		                     'expires_at': source.get( 'expires_at', '' ),
		                     'last_active_at': source.get( 'last_active_at', '' ),
		                     'object': source.get( 'object', '' ),
		                     'metadata': source.get( 'metadata', { } ) } )
	return normalized

normalize_vector_store_file_rows

normalize_vector_store_file_rows(
    rows: Any,
) -> List[Dict[str, Any]]

Normalize vector store file rows.

Purpose

Normalizes the vector store file rows input into the stable shape expected by downstream Gipity helpers and display logic.

Parameters:

Name Type Description Default
rows Any

Value supplied to the helper.

required

Returns:

Type Description
List[Dict[str, Any]]

Value produced by the normalize_vector_store_file_rows helper according to its function

List[Dict[str, Any]]

annotation and return statements.

Source code in app.py
def normalize_vector_store_file_rows( rows: Any ) -> List[ Dict[ str, Any ] ]:
	"""Normalize vector store file rows.

        Purpose:
            Normalizes the vector store file rows input into the stable shape expected by downstream
            Gipity helpers and display logic.

        Args:
            rows (Any): Value supplied to the helper.

        Returns:
            Value produced by the normalize_vector_store_file_rows helper according to its function
            annotation and return statements.
    """
	if rows is None:
		return [ ]
	if isinstance( rows, dict ) and isinstance( rows.get( 'data' ), list ):
		items = rows.get( 'data', [ ] )
	elif isinstance( rows, list ):
		items = rows
	else:
		items = getattr( rows, 'data', [ ] )
	normalized: List[ Dict[ str, Any ] ] = [ ]
	for item in items:
		if isinstance( item, dict ):
			source = item
		elif hasattr( item, 'model_dump' ):
			try:
				source = item.model_dump( )
			except Exception as e:
				exception = Error( e )
				exception.module = 'app'
				exception.cause = 'normalize_vector_store_file_rows'
				exception.method = 'normalize_vector_store_file_rows( ... )'
				Logger( ).write( exception )
				source = { }
		else:
			source = { 'id': getattr( item, 'id', None ), 'object': getattr( item, 'object', None ),
			           'created_at': getattr( item, 'created_at', None ),
			           'vector_store_id': getattr( item, 'vector_store_id', None ),
			           'status': getattr( item, 'status', None ),
			           'last_error': getattr( item, 'last_error', None ),
			           'usage_bytes': getattr( item, 'usage_bytes', None ),
			           'attributes': getattr( item, 'attributes', None ) }
		file_id = source.get( 'id' )
		if not file_id:
			continue
		normalized.append( { 'id': file_id, 'vector_store_id': source.get( 'vector_store_id', '' ),
		                     'status': source.get( 'status', '' ),
		                     'usage_bytes': source.get( 'usage_bytes', 0 ),
		                     'created_at': source.get( 'created_at', '' ),
		                     'last_error': source.get( 'last_error', '' ),
		                     'attributes': source.get( 'attributes', { } ),
		                     'object': source.get( 'object', '' ),
		                     'chunking_strategy': source.get( 'chunking_strategy', { } ) } )
	return normalized

build_vector_stores_dataframe

build_vector_stores_dataframe(
    rows: List[Dict[str, Any]],
) -> pd.DataFrame

Build vector stores dataframe.

Purpose

Builds the vector stores dataframe value used by the Gipity interface or provider wrapper. The function normalizes inputs and returns a stable object for downstream use.

Parameters:

Name Type Description Default
rows List[Dict[str, Any]]

Value supplied to the helper.

required

Returns:

Type Description
DataFrame

Value produced by the build_vector_stores_dataframe helper according to its function

DataFrame

annotation and return statements.

Source code in app.py
def build_vector_stores_dataframe( rows: List[ Dict[ str, Any ] ] ) -> pd.DataFrame:
	"""Build vector stores dataframe.

        Purpose:
            Builds the vector stores dataframe value used by the Gipity interface or provider
            wrapper. The function normalizes inputs and returns a stable object for downstream use.

        Args:
            rows (List[Dict[str, Any]]): Value supplied to the helper.

        Returns:
            Value produced by the build_vector_stores_dataframe helper according to its function
            annotation and return statements.
    """
	if not isinstance( rows, list ) or len( rows ) == 0:
		return pd.DataFrame( )
	df_stores = pd.DataFrame( rows )
	preferred = [ 'id', 'name', 'description', 'status', 'usage_bytes', 'file_counts', 'created_at',
	              'expires_at', 'last_active_at', 'object', 'metadata' ]
	columns = [ column for column in preferred if column in df_stores.columns ]
	extras = [ column for column in df_stores.columns if column not in columns ]
	return df_stores[ columns + extras ]

build_vector_store_files_dataframe

build_vector_store_files_dataframe(
    rows: List[Dict[str, Any]],
) -> pd.DataFrame

Build vector store files dataframe.

Purpose

Builds the vector store files dataframe value used by the Gipity interface or provider wrapper. The function normalizes inputs and returns a stable object for downstream use.

Parameters:

Name Type Description Default
rows List[Dict[str, Any]]

Value supplied to the helper.

required

Returns:

Type Description
DataFrame

Value produced by the build_vector_store_files_dataframe helper according to its

DataFrame

function annotation and return statements.

Source code in app.py
def build_vector_store_files_dataframe( rows: List[ Dict[ str, Any ] ] ) -> pd.DataFrame:
	"""Build vector store files dataframe.

        Purpose:
            Builds the vector store files dataframe value used by the Gipity interface or provider
            wrapper. The function normalizes inputs and returns a stable object for downstream use.

        Args:
            rows (List[Dict[str, Any]]): Value supplied to the helper.

        Returns:
            Value produced by the build_vector_store_files_dataframe helper according to its
            function annotation and return statements.
    """
	if not isinstance( rows, list ) or len( rows ) == 0:
		return pd.DataFrame( )
	df_files = pd.DataFrame( rows )
	preferred = [ 'id', 'vector_store_id', 'status', 'usage_bytes', 'created_at', 'last_error',
	              'attributes', 'object', 'chunking_strategy' ]
	columns = [ column for column in preferred if column in df_files.columns ]
	extras = [ column for column in df_files.columns if column not in columns ]
	return df_files[ columns + extras ]

build_vector_store_selection_options

build_vector_store_selection_options(
    rows: List[Dict[str, Any]],
) -> Dict[str, str]

Build vector store selection options.

Purpose

Builds the vector store selection options value used by the Gipity interface or provider wrapper. The function normalizes inputs and returns a stable object for downstream use.

Parameters:

Name Type Description Default
rows List[Dict[str, Any]]

Value supplied to the helper.

required

Returns:

Type Description
Dict[str, str]

Value produced by the build_vector_store_selection_options helper according to its

Dict[str, str]

function annotation and return statements.

Source code in app.py
def build_vector_store_selection_options( rows: List[ Dict[ str, Any ] ] ) -> Dict[ str, str ]:
	"""Build vector store selection options.

        Purpose:
            Builds the vector store selection options value used by the Gipity interface or provider
            wrapper. The function normalizes inputs and returns a stable object for downstream use.

        Args:
            rows (List[Dict[str, Any]]): Value supplied to the helper.

        Returns:
            Value produced by the build_vector_store_selection_options helper according to its
            function annotation and return statements.
    """
	options: Dict[ str, str ] = { }
	if not isinstance( rows, list ):
		return options
	for row in rows:
		if not isinstance( row, dict ):
			continue
		store_id = row.get( 'id' )
		if not isinstance( store_id, str ) or not store_id.strip( ):
			continue
		name = row.get( 'name' ) or 'Unnamed store'
		status = row.get( 'status' ) or 'unknown'
		label = f'{name} — {store_id} — {status}'
		options[ label ] = store_id
	return options

get_selected_vector_store_id

get_selected_vector_store_id(
    selected_label: str | None,
    options: Dict[str, str] | None = None,
) -> str | None

Get selected vector store id.

Purpose

Returns the selected vector store id value used by the Gipity interface. The helper centralizes option lookup and fallback behavior for callers.

Parameters:

Name Type Description Default
selected_label str | None

Value supplied to the helper.

required
options Dict[str, str] | None

Value supplied to the helper.

None

Returns:

Type Description
str | None

Value produced by the get_selected_vector_store_id helper according to its function

str | None

annotation and return statements.

Source code in app.py
def get_selected_vector_store_id( selected_label: str | None,
		options: Dict[ str, str ] | None = None ) -> str | None:
	"""Get selected vector store id.

        Purpose:
            Returns the selected vector store id value used by the Gipity interface. The helper
            centralizes option lookup and fallback behavior for callers.

        Args:
            selected_label (str | None): Value supplied to the helper.
            options (Dict[str, str] | None): Value supplied to the helper.

        Returns:
            Value produced by the get_selected_vector_store_id helper according to its function
            annotation and return statements.
    """
	if not isinstance( selected_label, str ) or not selected_label.strip( ):
		return None
	value = selected_label.strip( )
	if isinstance( options, dict ) and value in options:
		return options[ value ]
	if value.startswith( 'vs_' ):
		return value
	return None

build_vector_store_file_selection_options

build_vector_store_file_selection_options(
    rows: List[Dict[str, Any]],
) -> Dict[str, str]

Build vector store file selection options.

Purpose

Builds the vector store file selection options value used by the Gipity interface or provider wrapper. The function normalizes inputs and returns a stable object for downstream use.

Parameters:

Name Type Description Default
rows List[Dict[str, Any]]

Value supplied to the helper.

required

Returns:

Type Description
Dict[str, str]

Value produced by the build_vector_store_file_selection_options helper according to its

Dict[str, str]

function annotation and return statements.

Source code in app.py
def build_vector_store_file_selection_options( rows: List[ Dict[ str, Any ] ] ) -> Dict[ str, str ]:
	"""Build vector store file selection options.

        Purpose:
            Builds the vector store file selection options value used by the Gipity interface or
            provider wrapper. The function normalizes inputs and returns a stable object for
            downstream use.

        Args:
            rows (List[Dict[str, Any]]): Value supplied to the helper.

        Returns:
            Value produced by the build_vector_store_file_selection_options helper according to its
            function annotation and return statements.
    """
	options: Dict[ str, str ] = { }
	if not isinstance( rows, list ):
		return options
	for row in rows:
		if not isinstance( row, dict ):
			continue
		file_id = row.get( 'id' )
		if not isinstance( file_id, str ) or not file_id.strip( ):
			continue
		status = row.get( 'status' ) or 'unknown'
		label = f'{file_id} — {status}'
		options[ label ] = file_id
	return options

get_selected_vector_store_file_id

get_selected_vector_store_file_id(
    selected_label: str | None,
    options: Dict[str, str] | None = None,
) -> str | None

Get selected vector store file id.

Purpose

Returns the selected vector store file id value used by the Gipity interface. The helper centralizes option lookup and fallback behavior for callers.

Parameters:

Name Type Description Default
selected_label str | None

Value supplied to the helper.

required
options Dict[str, str] | None

Value supplied to the helper.

None

Returns:

Type Description
str | None

Value produced by the get_selected_vector_store_file_id helper according to its function

str | None

annotation and return statements.

Source code in app.py
def get_selected_vector_store_file_id( selected_label: str | None,
		options: Dict[ str, str ] | None = None ) -> str | None:
	"""Get selected vector store file id.

        Purpose:
            Returns the selected vector store file id value used by the Gipity interface. The helper
            centralizes option lookup and fallback behavior for callers.

        Args:
            selected_label (str | None): Value supplied to the helper.
            options (Dict[str, str] | None): Value supplied to the helper.

        Returns:
            Value produced by the get_selected_vector_store_file_id helper according to its function
            annotation and return statements.
    """
	if not isinstance( selected_label, str ) or not selected_label.strip( ):
		return None
	value = selected_label.strip( )
	if isinstance( options, dict ) and value in options:
		return options[ value ]
	if value.startswith( 'file-' ):
		return value
	return None

render_vector_stores_table

render_vector_stores_table(
    rows: List[Dict[str, Any]],
) -> None

Render vector stores table.

Purpose

Renders the vector stores table user-interface section or display element in Streamlit while preserving the application state expected by the surrounding workflow.

Parameters:

Name Type Description Default
rows List[Dict[str, Any]]

Value supplied to the helper.

required
Source code in app.py
def render_vector_stores_table( rows: List[ Dict[ str, Any ] ] ) -> None:
	"""Render vector stores table.

        Purpose:
            Renders the vector stores table user-interface section or display element in Streamlit
            while preserving the application state expected by the surrounding workflow.

        Args:
            rows (List[Dict[str, Any]]): Value supplied to the helper.
    """
	df_stores = build_vector_stores_dataframe( rows )
	st.session_state[ 'stores_df' ] = df_stores
	if df_stores.empty:
		st.info( 'No vector stores available.' )
		return
	st.data_editor( df_stores, use_container_width=True, hide_index=True )

render_vector_store_metadata

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

Render vector store metadata.

Purpose

Renders the vector store metadata user-interface section or display element in Streamlit while preserving the application state expected by the surrounding workflow.

Parameters:

Name Type Description Default
metadata Dict[str, Any] | None

Value supplied to the helper.

required
Source code in app.py
def render_vector_store_metadata( metadata: Dict[ str, Any ] | None ) -> None:
	"""Render vector store metadata.

        Purpose:
            Renders the vector store metadata user-interface section or display element in Streamlit
            while preserving the application state expected by the surrounding workflow.

        Args:
            metadata (Dict[str, Any] | None): Value supplied to the helper.
    """
	if not isinstance( metadata, dict ) or len( metadata ) == 0:
		st.info( 'No vector store metadata available.' )
		return
	m1, m2, m3, m4 = st.columns( [ 0.25, 0.25, 0.25, 0.25 ], border=True, gap='xxsmall' )
	with m1:
		st.metric( 'Status', metadata.get( 'status', '—' ) or '—' )
	with m2:
		st.metric( 'Usage Bytes', metadata.get( 'usage_bytes', 0 ) or 0 )
	with m3:
		st.metric( 'Object', metadata.get( 'object', '—' ) or '—' )
	with m4:
		file_counts = metadata.get( 'file_counts', { } )
		if isinstance( file_counts, dict ):
			st.metric( 'Files', file_counts.get( 'total', 0 ) or 0 )
		else:
			st.metric( 'Files', '—' )
	st.json( metadata )

render_vector_store_files_table

render_vector_store_files_table(
    rows: List[Dict[str, Any]],
) -> None

Render vector store files table.

Purpose

Renders the vector store files table user-interface section or display element in Streamlit while preserving the application state expected by the surrounding workflow.

Parameters:

Name Type Description Default
rows List[Dict[str, Any]]

Value supplied to the helper.

required
Source code in app.py
def render_vector_store_files_table( rows: List[ Dict[ str, Any ] ] ) -> None:
	"""Render vector store files table.

        Purpose:
            Renders the vector store files table user-interface section or display element in
            Streamlit while preserving the application state expected by the surrounding workflow.

        Args:
            rows (List[Dict[str, Any]]): Value supplied to the helper.
    """
	df_files = build_vector_store_files_dataframe( rows )
	st.session_state[ 'stores_files_df' ] = df_files
	if df_files.empty:
		st.info( 'No vector store files available.' )
		return
	st.data_editor( df_files, use_container_width=True, hide_index=True )

render_vector_store_search_results

render_vector_store_search_results(
    results: List[Dict[str, Any]],
) -> None

Render vector store search results.

Purpose

Renders the vector store search results user-interface section or display element in Streamlit while preserving the application state expected by the surrounding workflow.

Parameters:

Name Type Description Default
results List[Dict[str, Any]]

Value supplied to the helper.

required
Source code in app.py
def render_vector_store_search_results( results: List[ Dict[ str, Any ] ] ) -> None:
	"""Render vector store search results.

        Purpose:
            Renders the vector store search results user-interface section or display element in
            Streamlit while preserving the application state expected by the surrounding workflow.

        Args:
            results (List[Dict[str, Any]]): Value supplied to the helper.
    """
	if not isinstance( results, list ) or len( results ) == 0:
		st.info( 'No search results available.' )
		return
	df_results = pd.DataFrame( results )
	st.data_editor( df_results, use_container_width=True, hide_index=True )

render_vector_store_batch_result

render_vector_store_batch_result(
    result: Dict[str, Any] | None,
) -> None

Render vector store batch result.

Purpose

Renders the vector store batch result user-interface section or display element in Streamlit while preserving the application state expected by the surrounding workflow.

Parameters:

Name Type Description Default
result Dict[str, Any] | None

Value supplied to the helper.

required
Source code in app.py
def render_vector_store_batch_result( result: Dict[ str, Any ] | None ) -> None:
	"""Render vector store batch result.

        Purpose:
            Renders the vector store batch result user-interface section or display element in
            Streamlit while preserving the application state expected by the surrounding workflow.

        Args:
            result (Dict[str, Any] | None): Value supplied to the helper.
    """
	if not isinstance( result, dict ) or len( result ) == 0:
		st.info( 'No batch result available.' )
		return
	st.json( result )

clear_vector_store_outputs

clear_vector_store_outputs() -> None

Clear vector store outputs.

Purpose

Clears the vector store outputs state used by the current workflow so the user interface can start from a clean output state.

Source code in app.py
def clear_vector_store_outputs( ) -> None:
	"""Clear vector store outputs.

        Purpose:
            Clears the vector store outputs state used by the current workflow so the user interface
            can start from a clean output state.
    """
	st.session_state[ 'stores_store_metadata' ] = { }
	st.session_state[ 'stores_files_table' ] = [ ]
	st.session_state[ 'stores_files_df' ] = pd.DataFrame( )
	st.session_state[ 'stores_batch_result' ] = { }
	st.session_state[ 'stores_search_results' ] = [ ]
	st.session_state[ 'stores_last_answer' ] = ''

clear_vector_store_messages

clear_vector_store_messages() -> None

Clear vector store messages.

Purpose

Clears the vector store messages state used by the current workflow so the user interface can start from a clean output state.

Source code in app.py
def clear_vector_store_messages( ) -> None:
	"""Clear vector store messages.

        Purpose:
            Clears the vector store messages state used by the current workflow so the user
            interface can start from a clean output state.
    """
	st.session_state.stores_messages = [ ]

reset_vector_store_controls

reset_vector_store_controls() -> None

Reset vector store controls.

Purpose

Resets the vector store controls state used by the application. The function clears related Streamlit keys without performing provider calls.

Source code in app.py
def reset_vector_store_controls( ) -> None:
	"""Reset vector store controls.

        Purpose:
            Resets the vector store controls state used by the application. The function clears
            related Streamlit keys without performing provider calls.
    """
	for key in [ 'stores_model', 'stores_id', 'stores_manual_id', 'stores_selected_label',
	             'stores_name', 'stores_description', 'stores_metadata', 'stores_expires_days',
	             'stores_expires_anchor', 'stores_file_ids', 'stores_chunking_strategy',
	             'stores_chunk_size', 'stores_chunk_overlap', 'stores_file_id',
	             'stores_file_selected_label', 'stores_file_attributes', 'stores_batch_id',
	             'stores_search_query', 'stores_max_results', 'stores_ranker',
	             'stores_score_threshold', 'stores_rewrite_query' ]:
		if key in st.session_state:
			del st.session_state[ key ]

reset_vector_store_all

reset_vector_store_all() -> None

Reset vector store all.

Purpose

Resets the vector store all state used by the application. The function clears related Streamlit keys without performing provider calls.

Source code in app.py
def reset_vector_store_all( ) -> None:
	"""Reset vector store all.

        Purpose:
            Resets the vector store all state used by the application. The function clears related
            Streamlit keys without performing provider calls.
    """
	reset_vector_store_controls( )
	clear_vector_store_outputs( )
	st.session_state[ 'stores_table' ] = [ ]
	st.session_state[ 'stores_df' ] = pd.DataFrame( )
	st.session_state.stores_messages = [ ]

clear_vector_store_instructions

clear_vector_store_instructions() -> None

Clear vector store instructions.

Purpose

Clears the vector store instructions state used by the current workflow so the user interface can start from a clean output state.

Source code in app.py
def clear_vector_store_instructions( ) -> None:
	"""Clear vector store instructions.

        Purpose:
            Clears the vector store instructions state used by the current workflow so the user
            interface can start from a clean output state.
    """
	st.session_state[ 'stores_system_instructions' ] = ''
	st.session_state[ 'instructions' ] = ''

load_vector_store_instruction_template

load_vector_store_instruction_template() -> None

Load vector store instruction template.

Purpose

Loads the vector store instruction template resource or state required by the Gipity workflow and returns the prepared value for caller use.

Source code in app.py
def load_vector_store_instruction_template( ) -> None:
	"""Load vector store instruction template.

        Purpose:
            Loads the vector store instruction template resource or state required by the Gipity
            workflow and returns the prepared value for caller use.
    """
	name = st.session_state.get( 'instructions' )
	if name and name != 'No Templates Found':
		text = fetch_prompt_text( cfg.DB_PATH, name )
		if text is not None:
			st.session_state[ 'stores_system_instructions' ] = text

convert_vector_store_system_instructions

convert_vector_store_system_instructions() -> None

Convert vector store system instructions.

Purpose

Provides the convert vector store system instructions helper used by the Gipity Streamlit application. The function supports UI state management, provider coordination, data normalization, or display behavior required by the surrounding workflow.

Source code in app.py
def convert_vector_store_system_instructions( ) -> None:
	"""Convert vector store system instructions.

        Purpose:
            Provides the convert vector store system instructions helper used by the Gipity
            Streamlit application. The function supports UI state management, provider coordination,
            data normalization, or display behavior required by the surrounding workflow.
    """
	text = st.session_state.get( 'stores_system_instructions', '' )
	if not isinstance( text, str ) or not text.strip( ):
		return
	source = text.strip( )
	if cfg.XML_BLOCK_PATTERN.search( source ):
		converted = convert_xml( source )
	else:
		converted = convert_markdown( source )
	st.session_state[ 'stores_system_instructions' ] = converted

run_vector_store_create

run_vector_store_create(
    vector: VectorStores,
) -> Dict[str, Any]

Run vector store create.

Purpose

Runs the vector store create workflow from the Streamlit interface by validating current inputs, calling the appropriate wrapper or helper, and storing relevant output state.

Parameters:

Name Type Description Default
vector VectorStores

Value supplied to the helper.

required

Returns:

Type Description
Dict[str, Any]

Value produced by the run_vector_store_create helper according to its function

Dict[str, Any]

annotation and return statements.

Source code in app.py
def run_vector_store_create( vector: VectorStores ) -> Dict[ str, Any ]:
	"""Run vector store create.

        Purpose:
            Runs the vector store create workflow from the Streamlit interface by validating current
            inputs, calling the appropriate wrapper or helper, and storing relevant output state.

        Args:
            vector (VectorStores): Value supplied to the helper.

        Returns:
            Value produced by the run_vector_store_create helper according to its function
            annotation and return statements.
    """
	name = st.session_state.get( 'stores_name', '' )
	if not isinstance( name, str ) or not name.strip( ):
		st.warning( 'Enter a vector store name before creating a store.' )
		return { }
	metadata = parse_vector_store_json( st.session_state.get( 'stores_metadata', '' ),
		label='Vector store metadata' )
	file_ids = parse_vector_store_file_ids( st.session_state.get( 'stores_file_ids', '' ) )
	result = vector.create( name=name.strip( ),
		description=st.session_state.get( 'stores_description', '' ) or None, metadata=metadata,
		expires_after=build_vector_store_expires_after_from_state( vector ), file_ids=file_ids,
		chunking_strategy=build_vector_store_chunking_strategy_from_state( vector ) )
	result = result if isinstance( result, dict ) else { }
	if result.get( 'id' ):
		st.session_state[ 'stores_id' ] = result.get( 'id' )
		st.session_state[ 'stores_store_metadata' ] = result
	return result

run_vector_store_list

run_vector_store_list(
    vector: VectorStores,
) -> List[Dict[str, Any]]

Run vector store list.

Purpose

Runs the vector store list workflow from the Streamlit interface by validating current inputs, calling the appropriate wrapper or helper, and storing relevant output state.

Parameters:

Name Type Description Default
vector VectorStores

Value supplied to the helper.

required

Returns:

Type Description
List[Dict[str, Any]]

Value produced by the run_vector_store_list helper according to its function annotation

List[Dict[str, Any]]

and return statements.

Source code in app.py
def run_vector_store_list( vector: VectorStores ) -> List[ Dict[ str, Any ] ]:
	"""Run vector store list.

        Purpose:
            Runs the vector store list workflow from the Streamlit interface by validating current
            inputs, calling the appropriate wrapper or helper, and storing relevant output state.

        Args:
            vector (VectorStores): Value supplied to the helper.

        Returns:
            Value produced by the run_vector_store_list helper according to its function annotation
            and return statements.
    """
	rows = vector.list_stores( limit=100, order='desc' )
	rows = normalize_vector_store_rows( rows )
	st.session_state[ 'stores_table' ] = rows
	st.session_state[ 'stores_df' ] = build_vector_stores_dataframe( rows )
	return rows

run_vector_store_retrieve

run_vector_store_retrieve(
    vector: VectorStores, store_id: str | None
) -> Dict[str, Any]

Run vector store retrieve.

Purpose

Runs the vector store retrieve workflow from the Streamlit interface by validating current inputs, calling the appropriate wrapper or helper, and storing relevant output state.

Parameters:

Name Type Description Default
vector VectorStores

Value supplied to the helper.

required
store_id str | None

Value supplied to the helper.

required

Returns:

Type Description
Dict[str, Any]

Value produced by the run_vector_store_retrieve helper according to its function

Dict[str, Any]

annotation and return statements.

Source code in app.py
def run_vector_store_retrieve( vector: VectorStores, store_id: str | None ) -> Dict[ str, Any ]:
	"""Run vector store retrieve.

        Purpose:
            Runs the vector store retrieve workflow from the Streamlit interface by validating
            current inputs, calling the appropriate wrapper or helper, and storing relevant output
            state.

        Args:
            vector (VectorStores): Value supplied to the helper.
            store_id (str | None): Value supplied to the helper.

        Returns:
            Value produced by the run_vector_store_retrieve helper according to its function
            annotation and return statements.
    """
	if not isinstance( store_id, str ) or not store_id.strip( ):
		st.warning( 'Select or enter a vector store ID before retrieving metadata.' )
		return { }
	result = vector.retrieve( store_id=store_id.strip( ) )
	result = result if isinstance( result, dict ) else { }
	st.session_state[ 'stores_store_metadata' ] = result
	st.session_state[ 'stores_id' ] = store_id.strip( )
	return result

run_vector_store_update

run_vector_store_update(
    vector: VectorStores, store_id: str | None
) -> Dict[str, Any]

Run vector store update.

Purpose

Runs the vector store update workflow from the Streamlit interface by validating current inputs, calling the appropriate wrapper or helper, and storing relevant output state.

Parameters:

Name Type Description Default
vector VectorStores

Value supplied to the helper.

required
store_id str | None

Value supplied to the helper.

required

Returns:

Type Description
Dict[str, Any]

Value produced by the run_vector_store_update helper according to its function

Dict[str, Any]

annotation and return statements.

Source code in app.py
def run_vector_store_update( vector: VectorStores, store_id: str | None ) -> Dict[ str, Any ]:
	"""Run vector store update.

        Purpose:
            Runs the vector store update workflow from the Streamlit interface by validating current
            inputs, calling the appropriate wrapper or helper, and storing relevant output state.

        Args:
            vector (VectorStores): Value supplied to the helper.
            store_id (str | None): Value supplied to the helper.

        Returns:
            Value produced by the run_vector_store_update helper according to its function
            annotation and return statements.
    """
	if not isinstance( store_id, str ) or not store_id.strip( ):
		st.warning( 'Select or enter a vector store ID before updating.' )
		return { }
	metadata = parse_vector_store_json( st.session_state.get( 'stores_metadata', '' ),
		label='Vector store metadata' )
	result = vector.update( store_id=store_id.strip( ),
		name=st.session_state.get( 'stores_name', '' ) or None,
		description=st.session_state.get( 'stores_description', '' ) or None, metadata=metadata,
		expires_after=build_vector_store_expires_after_from_state( vector ) )
	result = result if isinstance( result, dict ) else { }
	st.session_state[ 'stores_store_metadata' ] = result
	return result

run_vector_store_delete

run_vector_store_delete(
    vector: VectorStores, store_id: str | None
) -> Dict[str, Any]

Run vector store delete.

Purpose

Runs the vector store delete workflow from the Streamlit interface by validating current inputs, calling the appropriate wrapper or helper, and storing relevant output state.

Parameters:

Name Type Description Default
vector VectorStores

Value supplied to the helper.

required
store_id str | None

Value supplied to the helper.

required

Returns:

Type Description
Dict[str, Any]

Value produced by the run_vector_store_delete helper according to its function

Dict[str, Any]

annotation and return statements.

Source code in app.py
def run_vector_store_delete( vector: VectorStores, store_id: str | None ) -> Dict[ str, Any ]:
	"""Run vector store delete.

        Purpose:
            Runs the vector store delete workflow from the Streamlit interface by validating current
            inputs, calling the appropriate wrapper or helper, and storing relevant output state.

        Args:
            vector (VectorStores): Value supplied to the helper.
            store_id (str | None): Value supplied to the helper.

        Returns:
            Value produced by the run_vector_store_delete helper according to its function
            annotation and return statements.
    """
	if not isinstance( store_id, str ) or not store_id.strip( ):
		st.warning( 'Select or enter a vector store ID before deleting.' )
		return { }
	result = vector.delete( store_id=store_id.strip( ) )
	result = result if isinstance( result, dict ) else { }
	if result.get( 'deleted' ) is True:
		st.session_state[ 'stores_id' ] = ''
		st.session_state[ 'stores_store_metadata' ] = { }
	return result

run_vector_store_attach_file

run_vector_store_attach_file(
    vector: VectorStores, store_id: str | None
) -> Dict[str, Any]

Run vector store attach file.

Purpose

Runs the vector store attach file workflow from the Streamlit interface by validating current inputs, calling the appropriate wrapper or helper, and storing relevant output state.

Parameters:

Name Type Description Default
vector VectorStores

Value supplied to the helper.

required
store_id str | None

Value supplied to the helper.

required

Returns:

Type Description
Dict[str, Any]

Value produced by the run_vector_store_attach_file helper according to its function

Dict[str, Any]

annotation and return statements.

Source code in app.py
def run_vector_store_attach_file( vector: VectorStores, store_id: str | None ) -> Dict[ str, Any ]:
	"""Run vector store attach file.

        Purpose:
            Runs the vector store attach file workflow from the Streamlit interface by validating
            current inputs, calling the appropriate wrapper or helper, and storing relevant output
            state.

        Args:
            vector (VectorStores): Value supplied to the helper.
            store_id (str | None): Value supplied to the helper.

        Returns:
            Value produced by the run_vector_store_attach_file helper according to its function
            annotation and return statements.
    """
	if not isinstance( store_id, str ) or not store_id.strip( ):
		st.warning( 'Select or enter a vector store ID before attaching a file.' )
		return { }
	file_id = st.session_state.get( 'stores_file_id', '' )
	if not isinstance( file_id, str ) or not file_id.strip( ):
		st.warning( 'Enter an OpenAI file ID before attaching a file.' )
		return { }
	attributes = parse_vector_store_json( st.session_state.get( 'stores_file_attributes', '' ),
		label='Vector store file attributes' )
	result = vector.attach_file( store_id=store_id.strip( ), file_id=file_id.strip( ),
		attributes=attributes,
		chunking_strategy=build_vector_store_chunking_strategy_from_state( vector ) )
	return result if isinstance( result, dict ) else { }

run_vector_store_list_files

run_vector_store_list_files(
    vector: VectorStores, store_id: str | None
) -> List[Dict[str, Any]]

Run vector store list files.

Purpose

Runs the vector store list files workflow from the Streamlit interface by validating current inputs, calling the appropriate wrapper or helper, and storing relevant output state.

Parameters:

Name Type Description Default
vector VectorStores

Value supplied to the helper.

required
store_id str | None

Value supplied to the helper.

required

Returns:

Type Description
List[Dict[str, Any]]

Value produced by the run_vector_store_list_files helper according to its function

List[Dict[str, Any]]

annotation and return statements.

Source code in app.py
def run_vector_store_list_files( vector: VectorStores,
	store_id: str | None ) -> List[ Dict[ str, Any ] ]:
	"""Run vector store list files.

        Purpose:
            Runs the vector store list files workflow from the Streamlit interface by validating
            current inputs, calling the appropriate wrapper or helper, and storing relevant output
            state.

        Args:
            vector (VectorStores): Value supplied to the helper.
            store_id (str | None): Value supplied to the helper.

        Returns:
            Value produced by the run_vector_store_list_files helper according to its function
            annotation and return statements.
    """
	if not isinstance( store_id, str ) or not store_id.strip( ):
		st.warning( 'Select or enter a vector store ID before listing files.' )
		return [ ]
	rows = vector.list_files( store_id=store_id.strip( ), limit=100, order='desc' )
	rows = normalize_vector_store_file_rows( rows )
	st.session_state[ 'stores_files_table' ] = rows
	st.session_state[ 'stores_files_df' ] = build_vector_store_files_dataframe( rows )
	return rows

run_vector_store_delete_file

run_vector_store_delete_file(
    vector: VectorStores,
    store_id: str | None,
    file_id: str | None,
) -> Dict[str, Any]

Run vector store delete file.

Purpose

Runs the vector store delete file workflow from the Streamlit interface by validating current inputs, calling the appropriate wrapper or helper, and storing relevant output state.

Parameters:

Name Type Description Default
vector VectorStores

Value supplied to the helper.

required
store_id str | None

Value supplied to the helper.

required
file_id str | None

Value supplied to the helper.

required

Returns:

Type Description
Dict[str, Any]

Value produced by the run_vector_store_delete_file helper according to its function

Dict[str, Any]

annotation and return statements.

Source code in app.py
def run_vector_store_delete_file( vector: VectorStores, store_id: str | None,
		file_id: str | None ) -> Dict[ str, Any ]:
	"""Run vector store delete file.

        Purpose:
            Runs the vector store delete file workflow from the Streamlit interface by validating
            current inputs, calling the appropriate wrapper or helper, and storing relevant output
            state.

        Args:
            vector (VectorStores): Value supplied to the helper.
            store_id (str | None): Value supplied to the helper.
            file_id (str | None): Value supplied to the helper.

        Returns:
            Value produced by the run_vector_store_delete_file helper according to its function
            annotation and return statements.
    """
	if not isinstance( store_id, str ) or not store_id.strip( ):
		st.warning( 'Select or enter a vector store ID before deleting a file.' )
		return { }
	if not isinstance( file_id, str ) or not file_id.strip( ):
		st.warning( 'Select or enter a file ID before deleting it from the vector store.' )
		return { }
	result = vector.delete_file( store_id=store_id.strip( ), file_id=file_id.strip( ) )
	return result if isinstance( result, dict ) else { }

run_vector_store_create_batch

run_vector_store_create_batch(
    vector: VectorStores, store_id: str | None
) -> Dict[str, Any]

Run vector store create batch.

Purpose

Runs the vector store create batch workflow from the Streamlit interface by validating current inputs, calling the appropriate wrapper or helper, and storing relevant output state.

Parameters:

Name Type Description Default
vector VectorStores

Value supplied to the helper.

required
store_id str | None

Value supplied to the helper.

required

Returns:

Type Description
Dict[str, Any]

Value produced by the run_vector_store_create_batch helper according to its function

Dict[str, Any]

annotation and return statements.

Source code in app.py
def run_vector_store_create_batch( vector: VectorStores, store_id: str | None ) -> Dict[ str, Any ]:
	"""Run vector store create batch.

        Purpose:
            Runs the vector store create batch workflow from the Streamlit interface by validating
            current inputs, calling the appropriate wrapper or helper, and storing relevant output
            state.

        Args:
            vector (VectorStores): Value supplied to the helper.
            store_id (str | None): Value supplied to the helper.

        Returns:
            Value produced by the run_vector_store_create_batch helper according to its function
            annotation and return statements.
    """
	if not isinstance( store_id, str ) or not store_id.strip( ):
		st.warning( 'Select or enter a vector store ID before creating a batch.' )
		return { }
	file_ids = parse_vector_store_file_ids( st.session_state.get( 'stores_file_ids', '' ) )
	if len( file_ids ) == 0:
		st.warning( 'Enter one or more OpenAI file IDs before creating a batch.' )
		return { }
	attributes = parse_vector_store_json( st.session_state.get( 'stores_file_attributes', '' ),
		label='Vector store file attributes' )
	result = vector.create_file_batch( store_id=store_id.strip( ), file_ids=file_ids,
		attributes=attributes,
		chunking_strategy=build_vector_store_chunking_strategy_from_state( vector ) )
	result = result if isinstance( result, dict ) else { }
	st.session_state[ 'stores_batch_result' ] = result
	if result.get( 'id' ):
		st.session_state[ 'stores_batch_id' ] = result.get( 'id' )
	return result

run_vector_store_retrieve_batch

run_vector_store_retrieve_batch(
    vector: VectorStores, store_id: str | None
) -> Dict[str, Any]

Run vector store retrieve batch.

Purpose

Runs the vector store retrieve batch workflow from the Streamlit interface by validating current inputs, calling the appropriate wrapper or helper, and storing relevant output state.

Parameters:

Name Type Description Default
vector VectorStores

Value supplied to the helper.

required
store_id str | None

Value supplied to the helper.

required

Returns:

Type Description
Dict[str, Any]

Value produced by the run_vector_store_retrieve_batch helper according to its function

Dict[str, Any]

annotation and return statements.

Source code in app.py
def run_vector_store_retrieve_batch( vector: VectorStores, store_id: str | None ) -> Dict[ str, Any ]:
	"""Run vector store retrieve batch.

        Purpose:
            Runs the vector store retrieve batch workflow from the Streamlit interface by validating
            current inputs, calling the appropriate wrapper or helper, and storing relevant output
            state.

        Args:
            vector (VectorStores): Value supplied to the helper.
            store_id (str | None): Value supplied to the helper.

        Returns:
            Value produced by the run_vector_store_retrieve_batch helper according to its function
            annotation and return statements.
    """
	if not isinstance( store_id, str ) or not store_id.strip( ):
		st.warning( 'Select or enter a vector store ID before retrieving a batch.' )
		return { }
	batch_id = st.session_state.get( 'stores_batch_id', '' )
	if not isinstance( batch_id, str ) or not batch_id.strip( ):
		st.warning( 'Enter a file batch ID before retrieving batch metadata.' )
		return { }
	result = vector.retrieve_file_batch( store_id=store_id.strip( ), batch_id=batch_id.strip( ) )
	result = result if isinstance( result, dict ) else { }
	st.session_state[ 'stores_batch_result' ] = result
	return result

run_vector_store_cancel_batch

run_vector_store_cancel_batch(
    vector: VectorStores, store_id: str | None
) -> Dict[str, Any]

Run vector store cancel batch.

Purpose

Runs the vector store cancel batch workflow from the Streamlit interface by validating current inputs, calling the appropriate wrapper or helper, and storing relevant output state.

Parameters:

Name Type Description Default
vector VectorStores

Value supplied to the helper.

required
store_id str | None

Value supplied to the helper.

required

Returns:

Type Description
Dict[str, Any]

Value produced by the run_vector_store_cancel_batch helper according to its function

Dict[str, Any]

annotation and return statements.

Source code in app.py
def run_vector_store_cancel_batch( vector: VectorStores, store_id: str | None ) -> Dict[ str, Any ]:
	"""Run vector store cancel batch.

        Purpose:
            Runs the vector store cancel batch workflow from the Streamlit interface by validating
            current inputs, calling the appropriate wrapper or helper, and storing relevant output
            state.

        Args:
            vector (VectorStores): Value supplied to the helper.
            store_id (str | None): Value supplied to the helper.

        Returns:
            Value produced by the run_vector_store_cancel_batch helper according to its function
            annotation and return statements.
    """
	if not isinstance( store_id, str ) or not store_id.strip( ):
		st.warning( 'Select or enter a vector store ID before cancelling a batch.' )
		return { }
	batch_id = st.session_state.get( 'stores_batch_id', '' )
	if not isinstance( batch_id, str ) or not batch_id.strip( ):
		st.warning( 'Enter a file batch ID before cancelling a batch.' )
		return { }
	result = vector.cancel_file_batch( store_id=store_id.strip( ), batch_id=batch_id.strip( ) )
	result = result if isinstance( result, dict ) else { }
	st.session_state[ 'stores_batch_result' ] = result
	return result
run_vector_store_search(
    vector: VectorStores, store_id: str | None
) -> List[Dict[str, Any]]

Run vector store search.

Purpose

Runs the vector store search workflow from the Streamlit interface by validating current inputs, calling the appropriate wrapper or helper, and storing relevant output state.

Parameters:

Name Type Description Default
vector VectorStores

Value supplied to the helper.

required
store_id str | None

Value supplied to the helper.

required

Returns:

Type Description
List[Dict[str, Any]]

Value produced by the run_vector_store_search helper according to its function

List[Dict[str, Any]]

annotation and return statements.

Source code in app.py
def run_vector_store_search( vector: VectorStores, store_id: str | None ) -> List[ Dict[ str, Any ] ]:
	"""Run vector store search.

        Purpose:
            Runs the vector store search workflow from the Streamlit interface by validating current
            inputs, calling the appropriate wrapper or helper, and storing relevant output state.

        Args:
            vector (VectorStores): Value supplied to the helper.
            store_id (str | None): Value supplied to the helper.

        Returns:
            Value produced by the run_vector_store_search helper according to its function
            annotation and return statements.
    """
	if not isinstance( store_id, str ) or not store_id.strip( ):
		st.warning( 'Select or enter a vector store ID before searching.' )
		return [ ]
	query = st.session_state.get( 'stores_search_query', '' )
	if not isinstance( query, str ) or not query.strip( ):
		st.warning( 'Enter a search query before searching a vector store.' )
		return [ ]
	results = vector.search_store( store_id=store_id.strip( ), query=query.strip( ),
		max_num_results=st.session_state.get( 'stores_max_results', 10 ),
		ranking_options=build_vector_store_ranking_options_from_state( ),
		rewrite_query=st.session_state.get( 'stores_rewrite_query', False ) )
	results = results if isinstance( results, list ) else [ ]
	st.session_state[ 'stores_search_results' ] = results
	return results

run_vector_store_answer

run_vector_store_answer(
    vector: VectorStores,
    store_id: str | None,
    prompt: str | None,
) -> str | None

Run vector store answer.

Purpose

Runs the vector store answer workflow from the Streamlit interface by validating current inputs, calling the appropriate wrapper or helper, and storing relevant output state.

Parameters:

Name Type Description Default
vector VectorStores

Value supplied to the helper.

required
store_id str | None

Value supplied to the helper.

required
prompt str | None

Value supplied to the helper.

required

Returns:

Type Description
str | None

Value produced by the run_vector_store_answer helper according to its function

str | None

annotation and return statements.

Source code in app.py
def run_vector_store_answer( vector: VectorStores, store_id: str | None,
		prompt: str | None ) -> str | None:
	"""Run vector store answer.

        Purpose:
            Runs the vector store answer workflow from the Streamlit interface by validating current
            inputs, calling the appropriate wrapper or helper, and storing relevant output state.

        Args:
            vector (VectorStores): Value supplied to the helper.
            store_id (str | None): Value supplied to the helper.
            prompt (str | None): Value supplied to the helper.

        Returns:
            Value produced by the run_vector_store_answer helper according to its function
            annotation and return statements.
    """
	if not isinstance( store_id, str ) or not store_id.strip( ):
		st.warning( 'Select or enter a vector store ID before asking a question.' )
		return None
	if not isinstance( prompt, str ) or not prompt.strip( ):
		st.warning( 'Enter a prompt before querying the vector store.' )
		return None
	model = st.session_state.get( 'stores_model' ) or 'gpt-4o-mini'
	instructions = st.session_state.get( 'stores_system_instructions', '' )
	answer = vector.answer_with_file_search( store_ids=[ store_id.strip( ) ],
		prompt=prompt.strip( ), model=model,
		max_num_results=st.session_state.get( 'stores_max_results', 10 ),
		instructions=instructions if isinstance( instructions,
			str ) and instructions.strip( ) else None )
	if isinstance( answer, str ) and answer.strip( ):
		st.session_state[ 'stores_last_answer' ] = answer.strip( )
		return answer.strip( )
	return answer

initialize_database

initialize_database() -> None

Initialize the application database.

Purpose

Creates the Gipity application tables and ensures that the Prompts table uses the authoritative ID, Title, Name, Category, and Text schema. Existing compatible prompt records are preserved when a legacy Prompts schema must be migrated.

Returns:

Name Type Description
None None

The function creates or updates persistent SQLite database structures.

Raises:

Type Description
Error

Raised when database initialization or Prompts-table migration fails.

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

	Purpose:
	    Creates the Gipity application tables and ensures that the Prompts table uses the
	    authoritative ID, Title, Name, Category, and Text schema. Existing compatible prompt
	    records are preserved when a legacy Prompts schema must be migrated.

	Returns:
	    None: The function creates or updates persistent SQLite database structures.

	Raises:
	    Error: Raised when database initialization or Prompts-table migration fails.
	"""
	try:
		database_path = Path( cfg.DB_PATH )
		database_path.parent.mkdir( parents=True, exist_ok=True )
		with sqlite3.connect( str( database_path ) ) as conn:
			# ------------------------------------------------------------------
			# Transaction Configuration
			# ------------------------------------------------------------------
			conn.execute( 'PRAGMA foreign_keys = ON;' )

			# ------------------------------------------------------------------
			# Chat History
			# ------------------------------------------------------------------
			conn.execute( '''
                          CREATE TABLE IF NOT EXISTS "chat_history"
                          (
                              "id"
                              INTEGER
                              PRIMARY
                              KEY
                              AUTOINCREMENT,
                              "role"
                              TEXT,
                              "content"
                              TEXT
                          );
			              ''' )

			# ------------------------------------------------------------------
			# Embeddings
			# ------------------------------------------------------------------
			conn.execute( '''
                          CREATE TABLE IF NOT EXISTS "embeddings"
                          (
                              "id"
                              INTEGER
                              PRIMARY
                              KEY
                              AUTOINCREMENT,
                              "chunk"
                              TEXT,
                              "vector"
                              BLOB
                          );
			              ''' )

			# ------------------------------------------------------------------
			# Prompts Table Detection
			# ------------------------------------------------------------------
			prompt_table_exists = conn.execute( '''
                                                SELECT 1
                                                FROM "sqlite_master"
                                                WHERE "type" = 'table'
                                                  AND "name" = 'Prompts';
			                                    ''' ).fetchone( ) is not None

			required_columns: List[ str ] = [ 'ID', 'Title', 'Name', 'Category', 'Text', ]

			# ------------------------------------------------------------------
			# Create New Prompts Table
			# ------------------------------------------------------------------
			if not prompt_table_exists:
				conn.execute( '''
                              CREATE TABLE "Prompts"
                              (
                                  "ID"       INTEGER NOT NULL UNIQUE,
                                  "Title"    TEXT(80),
                                  "Name"     TEXT(80),
                                  "Category" TEXT(80),
                                  "Text"     TEXT(2040),
                                  PRIMARY KEY ("ID" AUTOINCREMENT)
                              );
				              ''' )

			else:
				# --------------------------------------------------------------
				# Inspect Existing Prompts Schema
				# --------------------------------------------------------------
				existing_schema = conn.execute( 'PRAGMA table_info("Prompts");' ).fetchall( )

				existing_columns = [ str( row[ 1 ] ) for row in existing_schema ]

				schema_requires_migration = (existing_columns != required_columns)

				if schema_requires_migration:
					# ----------------------------------------------------------
					# Read Existing Prompt Records
					# ----------------------------------------------------------
					cursor = conn.execute( 'SELECT * FROM "Prompts";' )

					legacy_column_names = [ str( description[ 0 ] ) for description in
						cursor.description or [ ] ]

					legacy_rows = cursor.fetchall( )

					legacy_records: List[ Dict[ str, Any ] ] = [
						dict( zip( legacy_column_names, row ) ) for row in legacy_rows ]

					# ----------------------------------------------------------
					# Create Migration Table
					# ----------------------------------------------------------
					conn.execute( 'DROP TABLE IF EXISTS "Prompts__Migration";' )

					conn.execute( '''
                                  CREATE TABLE "Prompts__Migration"
                                  (
                                      "ID"       INTEGER NOT NULL UNIQUE,
                                      "Title"    TEXT(80),
                                      "Name"     TEXT(80),
                                      "Category" TEXT(80),
                                      "Text"     TEXT(2040),
                                      PRIMARY KEY ("ID" AUTOINCREMENT)
                                  );
					              ''' )

					# ----------------------------------------------------------
					# Migrate Existing Prompt Records
					# ----------------------------------------------------------
					for record in legacy_records:
						raw_id = record.get( 'ID' )
						raw_legacy_id = record.get( 'PromptsId' )

						prompt_id: Optional[ int ] = None

						for candidate in (raw_id, raw_legacy_id):
							if candidate is None:
								continue

							candidate_text = str( candidate ).strip( )

							if not candidate_text:
								continue

							try:
								candidate_id = int( candidate_text )
							except (TypeError, ValueError):
								continue

							if candidate_id > 0:
								prompt_id = candidate_id
								break

						title = str( record.get( 'Title',
							record.get( 'Caption', record.get( 'Name', '' ) ) ) or '' ).strip( )[
							:80 ]

						name = str( record.get( 'Name', '' ) or '' ).strip( )[ :80 ]

						category = str( record.get( 'Category', '' ) or '' ).strip( )[ :80 ]

						text = str( record.get( 'Text', '' ) or '' ).strip( )[ :2040 ]

						if prompt_id is None:
							conn.execute( '''
                                          INSERT INTO "Prompts__Migration"
                                          ("Title",
                                           "Name",
                                           "Category",
                                           "Text")
                                          VALUES (?, ?, ?, ?);
							              ''', (title, name, category, text,) )

						else:
							conn.execute( '''
								INSERT OR REPLACE INTO "Prompts__Migration"
								(
									"ID",
									"Title",
									"Name",
									"Category",
									"Text"
								)
								VALUES (?, ?, ?, ?, ?);
								''', (prompt_id, title, name, category, text,) )

					# ----------------------------------------------------------
					# Replace Legacy Prompts Table
					# ----------------------------------------------------------
					conn.execute( 'DROP TABLE "Prompts";' )

					conn.execute( '''
                                  ALTER TABLE "Prompts__Migration"
                                      RENAME TO "Prompts";
					              ''' )

			# ------------------------------------------------------------------
			# Prompt Indexes
			# ------------------------------------------------------------------
			conn.execute( '''
                          CREATE INDEX IF NOT EXISTS "IX_Prompts_Category"
                              ON "Prompts" ("Category");
			              ''' )

			conn.execute( '''
                          CREATE INDEX IF NOT EXISTS "IX_Prompts_Title"
                              ON "Prompts" ("Title");
			              ''' )

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

			conn.commit( )

	except Exception as e:
		exception = Error( e )
		exception.module = 'app'
		exception.cause = 'initialize_database'
		exception.method = 'initialize_database( ) -> None'
		Logger( ).write( exception )
		raise exception

create_connection

create_connection() -> sqlite3.Connection

Create connection.

Purpose

Creates the connection resource used by the application and returns the resulting metadata or connection object when applicable.

Returns:

Type Description
Connection

Value produced by the create_connection helper according to its function annotation and

Connection

return statements.

Source code in app.py
def create_connection( ) -> sqlite3.Connection:
	"""Create connection.

        Purpose:
            Creates the connection resource used by the application and returns the resulting
            metadata or connection object when applicable.

        Returns:
            Value produced by the create_connection helper according to its function annotation and
            return statements.
    """
	return sqlite3.connect( cfg.DB_PATH )

list_tables

list_tables() -> List[str]

List tables.

Purpose

Provides the list tables helper used by the Gipity Streamlit application. The function supports UI state management, provider coordination, data normalization, or display behavior required by the surrounding workflow.

Returns:

Type Description
List[str]

Value produced by the list_tables helper according to its function annotation and return

List[str]

statements.

Source code in app.py
def list_tables( ) -> List[ str ]:
	"""List tables.

        Purpose:
            Provides the list tables helper used by the Gipity Streamlit application. The function
            supports UI state management, provider coordination, data normalization, or display
            behavior required by the surrounding workflow.

        Returns:
            Value produced by the list_tables helper according to its function annotation and return
            statements.
    """
	with create_connection( ) as conn:
		_query = "SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;"
		rows = conn.execute( _query ).fetchall( )
		return [ r[ 0 ] for r in rows ]

create_schema

create_schema(table: str) -> List[Tuple]

Create schema.

Purpose

Creates the schema resource used by the application and returns the resulting metadata or connection object when applicable.

Parameters:

Name Type Description Default
table str

Value supplied to the helper.

required

Returns:

Type Description
List[Tuple]

Value produced by the create_schema helper according to its function annotation and

List[Tuple]

return statements.

Source code in app.py
def create_schema( table: str ) -> List[ Tuple ]:
	"""Create schema.

        Purpose:
            Creates the schema resource used by the application and returns the resulting metadata
            or connection object when applicable.

        Args:
            table (str): Value supplied to the helper.

        Returns:
            Value produced by the create_schema helper according to its function annotation and
            return statements.
    """
	with create_connection( ) as conn:
		return conn.execute( f'PRAGMA table_info("{table}");' ).fetchall( )

read_table

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

Read table.

Purpose

Provides the read table helper used by the Gipity Streamlit application. The function supports UI state management, provider coordination, data normalization, or display behavior required by the surrounding workflow.

Parameters:

Name Type Description Default
table str

Value supplied to the helper.

required
limit int

Value supplied to the helper.

None
offset int

Value supplied to the helper.

0

Returns:

Type Description
DataFrame

Value produced by the read_table helper according to its function annotation and return

DataFrame

statements.

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

        Purpose:
            Provides the read table helper used by the Gipity Streamlit application. The function
            supports UI state management, provider coordination, data normalization, or display
            behavior required by the surrounding workflow.

        Args:
            table (str): Value supplied to the helper.
            limit (int): Value supplied to the helper.
            offset (int): Value supplied to the helper.

        Returns:
            Value produced by the read_table helper according to its function annotation and return
            statements.
    """
	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:
		"""Scalarize.

            Purpose:
                Provides the scalarize helper used by the Gipity Streamlit application. The function
                supports UI state management, provider coordination, data normalization, or display
                behavior required by the surrounding workflow.

            Args:
                value (Any): Value supplied to the helper.

            Returns:
                Value produced by the _scalarize helper according to its function annotation and return
                statements.
        """
		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 as e:
				exception = Error( e )
				exception.module = 'app'
				exception.cause = '_scalarize'
				exception.method = '_scalarize( ... )'
				Logger( ).write( exception )
				return value.hex( )
		if isinstance( value, (list, tuple, set, dict) ):
			try:
				return str( normalize( value ) )
			except Exception as e:
				exception = Error( e )
				exception.module = 'app'
				exception.cause = '_scalarize'
				exception.method = '_scalarize( ... )'
				Logger( ).write( exception )
				return str( value )
		if hasattr( value, 'model_dump' ):
			try:
				return str( value.model_dump( ) )
			except Exception as e:
				exception = Error( e )
				exception.module = 'app'
				exception.cause = '_scalarize'
				exception.method = '_scalarize( ... )'
				Logger( ).write( 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 table user-interface section or display element in Streamlit while preserving the application state expected by the surrounding workflow.

Parameters:

Name Type Description Default
df DataFrame

Value supplied to the helper.

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

        Purpose:
            Renders the table user-interface section or display element in Streamlit while
            preserving the application state expected by the surrounding workflow.

        Args:
            df (pd.DataFrame): Value supplied to the helper.
    """
	if df is None:
		st.info( 'No data available.' )
		return
	try:
		st.data_editor( df, use_container_width=True )
		return
	except Exception as e:
		exception = Error( e )
		exception.module = 'app'
		exception.cause = 'render_table'
		exception.method = 'render_table( ... )'
		Logger( ).write( 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 )

make_display_safe

make_display_safe(df: DataFrame) -> pd.DataFrame

Make display safe.

Purpose

Provides the make display safe helper used by the Gipity Streamlit application. The function supports UI state management, provider coordination, data normalization, or display behavior required by the surrounding workflow.

Parameters:

Name Type Description Default
df DataFrame

Value supplied to the helper.

required

Returns:

Type Description
DataFrame

Value produced by the make_display_safe helper according to its function annotation and

DataFrame

return statements.

Source code in app.py
def make_display_safe( df: pd.DataFrame ) -> pd.DataFrame:
	"""Make display safe.

        Purpose:
            Provides the make display safe helper used by the Gipity Streamlit application. The
            function supports UI state management, provider coordination, data normalization, or
            display behavior required by the surrounding workflow.

        Args:
            df (pd.DataFrame): Value supplied to the helper.

        Returns:
            Value produced by the make_display_safe helper according to its function annotation and
            return statements.
    """
	display_df = df.copy( )
	for col in display_df.columns:
		display_df[ col ] = display_df[ col ].map( lambda x: '' if x is None else str( x ) )
	return display_df

drop_table

drop_table(table: str) -> None

Drop table.

Purpose

Deletes or removes the table resource requested by the caller while preserving safe guard checks.

Parameters:

Name Type Description Default
table str

Value supplied to the helper.

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

        Purpose:
            Deletes or removes the table resource requested by the caller while preserving safe
            guard checks.

        Args:
            table (str): Value supplied to the helper.
    """
	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 index resource used by the application and returns the resulting metadata or connection object when applicable.

Parameters:

Name Type Description Default
table str

Value supplied to the helper.

required
column str

Value supplied to the helper.

required

Raises:

Type Description
Error

Re-raised after the exception is wrapped and written to the application logger.

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

        Purpose:
            Creates the index resource used by the application and returns the resulting metadata or
            connection object when applicable.

        Args:
            table (str): Value supplied to the helper.
            column (str): Value supplied to the helper.

        Raises:
            Error: Re-raised after the exception is wrapped and written to the application logger.
    """
	if not table or not column:
		return
	tables = list_tables( )
	if table not in tables:
		raise ValueError( 'Invalid table name.' )
	schema = create_schema( table )
	valid_columns = [ col[ 1 ] for col in schema ]
	if column not in valid_columns:
		raise ValueError( 'Invalid column name.' )
	safe_index_name = re.sub( '[^0-9a-zA-Z_]+', '_', f'idx_{table}_{column}' )
	sql = f'CREATE INDEX IF NOT EXISTS "{safe_index_name}" ON "{table}"("{column}");'
	with create_connection( ) as conn:
		conn.execute( sql )
		conn.commit( )

apply_filters

apply_filters(df: DataFrame) -> pd.DataFrame

Apply filters.

Purpose

Provides the apply filters helper used by the Gipity Streamlit application. The function supports UI state management, provider coordination, data normalization, or display behavior required by the surrounding workflow.

Parameters:

Name Type Description Default
df DataFrame

Value supplied to the helper.

required

Returns:

Type Description
DataFrame

Value produced by the apply_filters helper according to its function annotation and

DataFrame

return statements.

Source code in app.py
def apply_filters( df: pd.DataFrame ) -> pd.DataFrame:
	"""Apply filters.

        Purpose:
            Provides the apply filters helper used by the Gipity Streamlit application. The function
            supports UI state management, provider coordination, data normalization, or display
            behavior required by the surrounding workflow.

        Args:
            df (pd.DataFrame): Value supplied to the helper.

        Returns:
            Value produced by the apply_filters helper according to its function annotation and
            return statements.
    """
	st.subheader( 'Advanced Filters' )
	conditions = [ ]
	col1, col2, col3 = st.columns( 3 )
	column = col1.selectbox( 'Column', df.columns )
	operator = col2.selectbox( 'Operator', [ '=', '!=', '>', '<', '>=', '<=', 'contains' ] )
	value = col3.text_input( 'Value' )
	if value:
		if operator == '=':
			df = df[ df[ column ] == value ]
		elif operator == '!=':
			df = df[ df[ column ] != value ]
		elif operator == '>':
			df = df[ df[ column ].astype( float ) > float( value ) ]
		elif operator == '<':
			df = df[ df[ column ].astype( float ) < float( value ) ]
		elif operator == '>=':
			df = df[ df[ column ].astype( float ) >= float( value ) ]
		elif operator == '<=':
			df = df[ df[ column ].astype( float ) <= float( value ) ]
		elif operator == 'contains':
			df = df[ df[ column ].astype( str ).str.contains( value ) ]
	return df

create_aggregation

create_aggregation(df: DataFrame)

Create aggregation.

Purpose

Creates the aggregation resource used by the application and returns the resulting metadata or connection object when applicable.

Parameters:

Name Type Description Default
df DataFrame

Value supplied to the helper.

required
Source code in app.py
def create_aggregation( df: pd.DataFrame ):
	"""Create aggregation.

        Purpose:
            Creates the aggregation resource used by the application and returns the resulting
            metadata or connection object when applicable.

        Args:
            df (pd.DataFrame): Value supplied to the helper.
    """
	st.subheader( 'Aggregation Engine' )
	numeric_cols = df.select_dtypes( include=[ 'number' ] ).columns.tolist( )
	if not numeric_cols:
		st.info( 'No numeric columns available.' )
		return
	col = st.selectbox( 'Column', numeric_cols )
	agg = st.selectbox( 'Aggregation', [ 'COUNT', 'SUM', 'AVG', 'MIN', 'MAX', 'MEDIAN' ] )
	if agg == 'COUNT':
		result = df[ col ].count( )
	elif agg == 'SUM':
		result = df[ col ].sum( )
	elif agg == 'AVG':
		result = df[ col ].mean( )
	elif agg == 'MIN':
		result = df[ col ].min( )
	elif agg == 'MAX':
		result = df[ col ].max( )
	elif agg == 'MEDIAN':
		result = df[ col ].median( )
	st.metric( 'Result', result )

create_visualization

create_visualization(df: DataFrame) -> None

Create visualization.

Purpose

Creates the visualization resource used by the application and returns the resulting metadata or connection object when applicable.

Parameters:

Name Type Description Default
df DataFrame

Value supplied to the helper.

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

        Purpose:
            Creates the visualization resource used by the application and returns the resulting
            metadata or connection object when applicable.

        Args:
            df (pd.DataFrame): Value supplied to the helper.
    """
	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 )

convert_dataframe

convert_dataframe(table_name: str, df: DataFrame)

Convert dataframe.

Purpose

Provides the convert dataframe helper used by the Gipity Streamlit application. The function supports UI state management, provider coordination, data normalization, or display behavior required by the surrounding workflow.

Parameters:

Name Type Description Default
table_name str

Value supplied to the helper.

required
df DataFrame

Value supplied to the helper.

required
Source code in app.py
def convert_dataframe( table_name: str, df: pd.DataFrame ):
	"""Convert dataframe.

        Purpose:
            Provides the convert dataframe helper used by the Gipity Streamlit application. The
            function supports UI state management, provider coordination, data normalization, or
            display behavior required by the surrounding workflow.

        Args:
            table_name (str): Value supplied to the helper.
            df (pd.DataFrame): Value supplied to the helper.
    """
	columns = [ ]
	for col in df.columns:
		sql_type = get_sqlite_type( df[ col ].dtype )
		safe_col = col.replace( ' ', '_' )
		columns.append( f'{safe_col} {sql_type}' )
	create_stmt = f"CREATE TABLE IF NOT EXISTS {table_name} ({', '.join( columns )});"
	with create_connection( ) as conn:
		conn.execute( create_stmt )
		conn.commit( )

get_sqlite_type

get_sqlite_type(dtype) -> str

Get sqlite type.

Purpose

Returns the sqlite type value used by the Gipity interface. The helper centralizes option lookup and fallback behavior for callers.

Parameters:

Name Type Description Default
dtype Any

Value supplied to the helper.

required

Returns:

Type Description
str

Value produced by the get_sqlite_type helper according to its function annotation and

str

return statements.

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

        Purpose:
            Returns the sqlite type value used by the Gipity interface. The helper centralizes
            option lookup and fallback behavior for callers.

        Args:
            dtype (Any): Value supplied to the helper.

        Returns:
            Value produced by the get_sqlite_type helper according to its function annotation and
            return statements.
    """
	dtype_str = str( dtype ).lower( )
	if 'int' in dtype_str:
		return 'INTEGER'
	if 'float' in dtype_str:
		return 'REAL'
	if 'bool' in dtype_str:
		return 'INTEGER'
	if 'datetime' in dtype_str:
		return 'TEXT'
	if 'category' in dtype_str:
		return 'TEXT'
	return 'TEXT'

create_custom_table

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

Create custom table.

Purpose

Creates the custom table resource used by the application and returns the resulting metadata or connection object when applicable.

Parameters:

Name Type Description Default
table_name str

Value supplied to the helper.

required
columns list

Value supplied to the helper.

required

Raises:

Type Description
Error

Re-raised after the exception is wrapped and written to the application logger.

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

        Purpose:
            Creates the custom table resource used by the application and returns the resulting
            metadata or connection object when applicable.

        Args:
            table_name (str): Value supplied to the helper.
            columns (list): Value supplied to the helper.

        Raises:
            Error: Re-raised after the exception is wrapped and written to the application logger.
    """
	if not table_name:
		raise ValueError( 'Table name required.' )
	if not re.match( '^[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( '^[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

Provides the is safe query helper used by the Gipity Streamlit application. The function supports UI state management, provider coordination, data normalization, or display behavior required by the surrounding workflow.

Parameters:

Name Type Description Default
query str

Value supplied to the helper.

required

Returns:

Type Description
bool

Value produced by the is_safe_query helper according to its function annotation and

bool

return statements.

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

        Purpose:
            Provides the is safe query helper used by the Gipity Streamlit application. The function
            supports UI state management, provider coordination, data normalization, or display
            behavior required by the surrounding workflow.

        Args:
            query (str): Value supplied to the helper.

        Returns:
            Value produced by the is_safe_query helper according to its function annotation and
            return statements.
    """
	if not query or not isinstance( query, str ):
		return False
	q = query.strip( ).lower( )
	if ';' in q[ :-1 ]:
		return False
	q = re.sub( '--.*?$', '', q, flags=re.MULTILINE )
	q = re.sub( '/\\*.*?\\*/', '', q, flags=re.DOTALL )
	q = q.strip( )
	allowed_starts = ('select', 'with', 'explain', 'pragma')
	if not q.startswith( allowed_starts ):
		return False
	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 identifier resource used by the application and returns the resulting metadata or connection object when applicable.

Parameters:

Name Type Description Default
name str

Value supplied to the helper.

required

Returns:

Type Description
str

Value produced by the create_identifier helper according to its function annotation and

str

return statements.

Raises:

Type Description
Error

Re-raised after the exception is wrapped and written to the application logger.

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

        Purpose:
            Creates the identifier resource used by the application and returns the resulting
            metadata or connection object when applicable.

        Args:
            name (str): Value supplied to the helper.

        Returns:
            Value produced by the create_identifier helper according to its function annotation and
            return statements.

        Raises:
            Error: Re-raised after the exception is wrapped and written to the application logger.
    """
	if not name or not isinstance( name, str ):
		raise ValueError( 'Invalid Identifier.' )
	safe = re.sub( '[^0-9a-zA-Z_]', '_', name.strip( ) )
	if not re.match( '^[A-Za-z_]', safe ):
		safe = f'_{safe}'
	if not safe:
		raise ValueError( 'Invalid identifier after sanitization.' )
	return safe

get_indexes

get_indexes(table: str) -> List[Any]

Get indexes.

Purpose

Returns the indexes value used by the Gipity interface. The helper centralizes option lookup and fallback behavior for callers.

Parameters:

Name Type Description Default
table str

Value supplied to the helper.

required

Returns:

Type Description
List[Any]

Value produced by the get_indexes helper according to its function annotation and return

List[Any]

statements.

Source code in app.py
def get_indexes( table: str ) -> List[ Any ]:
	"""Get indexes.

        Purpose:
            Returns the indexes value used by the Gipity interface. The helper centralizes option
            lookup and fallback behavior for callers.

        Args:
            table (str): Value supplied to the helper.

        Returns:
            Value produced by the get_indexes helper according to its function annotation and return
            statements.
    """
	with create_connection( ) as conn:
		rows = conn.execute( f'PRAGMA index_list("{table}");' ).fetchall( )
		return rows

add_column

add_column(table: str, column: str, col_type: str)

Add column.

Purpose

Provides the add column helper used by the Gipity Streamlit application. The function supports UI state management, provider coordination, data normalization, or display behavior required by the surrounding workflow.

Parameters:

Name Type Description Default
table str

Value supplied to the helper.

required
column str

Value supplied to the helper.

required
col_type str

Value supplied to the helper.

required
Source code in app.py
def add_column( table: str, column: str, col_type: str ):
	"""Add column.

        Purpose:
            Provides the add column helper used by the Gipity Streamlit application. The function
            supports UI state management, provider coordination, data normalization, or display
            behavior required by the surrounding workflow.

        Args:
            table (str): Value supplied to the helper.
            column (str): Value supplied to the helper.
            col_type (str): Value supplied to the helper.
    """
	column = create_identifier( column )
	col_type = col_type.upper( )
	with create_connection( ) as conn:
		conn.execute( f'ALTER TABLE "{table}" ADD COLUMN "{column}" {col_type};' )
		conn.commit( )

rename_column

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

Rename column.

Purpose

Provides the rename column helper used by the Gipity Streamlit application. The function supports UI state management, provider coordination, data normalization, or display behavior required by the surrounding workflow.

Parameters:

Name Type Description Default
table_name str

Value supplied to the helper.

required
old_name str

Value supplied to the helper.

required
new_name str

Value supplied to the helper.

required

Raises:

Type Description
Error

Re-raised after the exception is wrapped and written to the application logger.

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

        Purpose:
            Provides the rename column helper used by the Gipity Streamlit application. The function
            supports UI state management, provider coordination, data normalization, or display
            behavior required by the surrounding workflow.

        Args:
            table_name (str): Value supplied to the helper.
            old_name (str): Value supplied to the helper.
            new_name (str): Value supplied to the helper.

        Raises:
            Error: Re-raised after the exception is wrapped and written to the application logger.
    """
	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 as e:
			exception = Error( e )
			exception.module = 'app'
			exception.cause = 'rename_column'
			exception.method = 'rename_column( ... )'
			Logger( ).write( exception )
			pass
		row = conn.execute(
			"\n            SELECT sql\n            FROM sqlite_master\n            WHERE type ='table' AND name =?\n\t\t\t",
			(table_name,) ).fetchone( )
		if not row or not row[ 0 ]:
			raise ValueError( 'Table definition not found.' )
		create_sql = row[ 0 ]
		indexes = conn.execute(
			"\n            SELECT sql\n            FROM sqlite_master\n            WHERE type ='index' AND tbl_name=? AND sql IS NOT NULL\n\t\t\t",
			(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( )

create_profile_table

create_profile_table(table: str) -> str

Create profile table.

Purpose

Creates the profile table resource used by the application and returns the resulting metadata or connection object when applicable.

Parameters:

Name Type Description Default
table str

Value supplied to the helper.

required

Returns:

Type Description
str

Value produced by the create_profile_table helper according to its function annotation

str

and return statements.

Source code in app.py
def create_profile_table( table: str ) -> str:
	"""Create profile table.

        Purpose:
            Creates the profile table resource used by the application and returns the resulting
            metadata or connection object when applicable.

        Args:
            table (str): Value supplied to the helper.

        Returns:
            Value produced by the create_profile_table helper according to its function annotation
            and return statements.
    """
	df = read_table( table )
	profile_rows = [ ]
	total_rows = len( df )
	for col in df.columns:
		series = df[ col ]
		null_count = series.isna( ).sum( )
		distinct_count = series.nunique( dropna=True )
		row = { 'column': col, 'dtype': str( series.dtype ),
		        'null_%': round( null_count / total_rows * 100, 2 ) if total_rows else 0,
		        'distinct_%': round( distinct_count / total_rows * 100, 2 ) if total_rows else 0 }
		if pd.api.types.is_numeric_dtype( series ):
			row[ 'min' ] = series.min( )
			row[ 'max' ] = series.max( )
			row[ 'mean' ] = series.mean( )
		else:
			row[ 'min' ] = None
			row[ 'max' ] = None
			row[ 'mean' ] = None
		profile_rows.append( row )
	return pd.DataFrame( profile_rows )

drop_column

drop_column(table: str, column: str)

Drop column.

Purpose

Deletes or removes the column resource requested by the caller while preserving safe guard checks.

Parameters:

Name Type Description Default
table str

Value supplied to the helper.

required
column str

Value supplied to the helper.

required

Raises:

Type Description
Error

Re-raised after the exception is wrapped and written to the application logger.

Source code in app.py
def drop_column( table: str, column: str ):
	"""Drop column.

        Purpose:
            Deletes or removes the column resource requested by the caller while preserving safe
            guard checks.

        Args:
            table (str): Value supplied to the helper.
            column (str): Value supplied to the helper.

        Raises:
            Error: Re-raised after the exception is wrapped and written to the application logger.
    """
	if not table or not column:
		raise ValueError( 'Table and column required.' )
	with create_connection( ) as conn:
		row = conn.execute(
			"\n            SELECT sql\n            FROM sqlite_master\n            WHERE type ='table' AND name =?\n\t\t\t",
			(table,) ).fetchone( )
		if not row or not row[ 0 ]:
			raise ValueError( 'Table definition not found.' )
		create_sql = row[ 0 ]
		open_paren = create_sql.find( '(' )
		close_paren = create_sql.rfind( ')' )
		if open_paren == -1 or close_paren == -1:
			raise ValueError( 'Malformed CREATE TABLE statement.' )
		inner = create_sql[ open_paren + 1:close_paren ]
		column_defs = [ c.strip( ) for c in inner.split( ',' ) ]
		new_defs = [ ]
		for col_def in column_defs:
			col_name = col_def.split( )[ 0 ].strip( '"' )
			if col_name != column:
				new_defs.append( col_def )
		if len( new_defs ) == len( column_defs ):
			raise ValueError( 'Column not found.' )
		temp_table = f'{table}_rebuild_temp'
		new_create_sql = f'CREATE TABLE "{temp_table}" (' + ', '.join( new_defs ) + ');'
		conn.execute( 'BEGIN' )
		conn.execute( new_create_sql )
		remaining_cols = [ c.split( )[ 0 ].strip( '"' ) for c in new_defs ]
		col_list = ', '.join( [ f'"{c}"' for c in remaining_cols ] )
		conn.execute( f'INSERT INTO "{temp_table}" ({col_list}) SELECT {col_list} FROM "{table}";' )
		indexes = conn.execute(
			"\n            SELECT sql\n            FROM sqlite_master\n            WHERE type ='index' AND tbl_name=? AND sql IS NOT NULL\n\t\t\t",
			(table,) ).fetchall( )
		conn.execute( f'DROP TABLE "{table}";' )
		conn.execute( f'ALTER TABLE "{temp_table}" RENAME TO "{table}";' )
		for idx in indexes:
			idx_sql = idx[ 0 ]
			if column not in idx_sql:
				conn.execute( idx_sql )
		conn.commit( )

rename_table

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

Rename table.

Purpose

Provides the rename table helper used by the Gipity Streamlit application. The function supports UI state management, provider coordination, data normalization, or display behavior required by the surrounding workflow.

Parameters:

Name Type Description Default
old_name str

Value supplied to the helper.

required
new_name str

Value supplied to the helper.

required

Raises:

Type Description
Error

Re-raised after the exception is wrapped and written to the application logger.

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

        Purpose:
            Provides the rename table helper used by the Gipity Streamlit application. The function
            supports UI state management, provider coordination, data normalization, or display
            behavior required by the surrounding workflow.

        Args:
            old_name (str): Value supplied to the helper.
            new_name (str): Value supplied to the helper.

        Raises:
            Error: Re-raised after the exception is wrapped and written to the application logger.
    """
	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 as e:
			exception = Error( e )
			exception.module = 'app'
			exception.cause = 'rename_table'
			exception.method = 'rename_table( ... )'
			Logger( ).write( exception )
			pass
		row = conn.execute(
			"\n            SELECT sql\n            FROM sqlite_master\n            WHERE type ='table' AND name =?\n\t\t\t",
			(old_name,) ).fetchone( )
		if not row or not row[ 0 ]:
			raise ValueError( 'Table definition not found.' )
		create_sql = row[ 0 ]
		indexes = conn.execute(
			"\n            SELECT sql\n            FROM sqlite_master\n            WHERE type ='index' AND tbl_name=? AND sql IS NOT NULL\n\t\t\t",
			(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_records

fetch_prompt_records(
    db_path: str, categories: Optional[List[str]] = None
) -> List[Dict[str, Any]]

Retrieve prompt records.

Purpose

Reads prompt records from the authoritative Prompts table. Optional category filtering restricts the returned records while preserving stable integer prompt identifiers.

Parameters:

Name Type Description Default
db_path str

Path to the application SQLite database.

required
categories Optional[List[str]]

Categories used to restrict the returned records.

None

Returns:

Type Description
List[Dict[str, Any]]

List[Dict[str, Any]]: Prompt records containing ID, Title, Name, Category, and Text.

Raises:

Type Description
Error

Raised when prompt records cannot be retrieved.

Source code in app.py
def fetch_prompt_records( db_path: str,
	categories: Optional[ List[ str ] ] = None ) -> List[ Dict[ str, Any ] ]:
	"""Retrieve prompt records.

	Purpose:
	    Reads prompt records from the authoritative Prompts table. Optional category filtering
	    restricts the returned records while preserving stable integer prompt identifiers.

	Args:
	    db_path (str): Path to the application SQLite database.
	    categories (Optional[List[str]]): Categories used to restrict the returned records.

	Returns:
	    List[Dict[str, Any]]: Prompt records containing ID, Title, Name, Category, and Text.

	Raises:
	    Error: Raised when prompt records cannot be retrieved.
	"""
	try:
		throw_if( 'db_path', db_path )

		query = '''
                SELECT "ID",
                       "Title",
                       "Name",
                       "Category",
                       "Text"
                FROM "Prompts" \
		        '''

		parameters: List[ Any ] = [ ]

		if categories:
			normalized_categories = [ str( category ).strip( ) for category in categories if
				str( category ).strip( ) ]

			if normalized_categories:
				placeholders = ', '.join( [ '?' for _ in normalized_categories ] )

				query += f'''
					WHERE TRIM(COALESCE("Category", '')) COLLATE NOCASE
					      IN ({placeholders})
				'''

				parameters.extend( normalized_categories )

		query += '''
			ORDER BY
				COALESCE("Category", '') COLLATE NOCASE,
				COALESCE(NULLIF(TRIM("Title"), ''), "Name") COLLATE NOCASE,
				"ID";
		'''

		with sqlite3.connect( db_path ) as conn:
			conn.row_factory = sqlite3.Row
			rows = conn.execute( query, parameters ).fetchall( )

		return [ { 'ID': int( row[ 'ID' ] ), 'Title': str( row[ 'Title' ] or '' ).strip( ),
			'Name': str( row[ 'Name' ] or '' ).strip( ),
			'Category': str( row[ 'Category' ] or '' ).strip( ),
			'Text': str( row[ 'Text' ] or '' ), } for row in rows ]

	except Exception as e:
		exception = Error( e )
		exception.module = 'app'
		exception.cause = 'fetch_prompt_records'
		exception.method = ('fetch_prompt_records( db_path: str, '
		                    'categories: Optional[ List[ str ] ] = None ) '
		                    '-> List[ Dict[ str, Any ] ]')
		Logger( ).write( exception )
		raise exception

fetch_prompt_categories

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

Retrieve prompt categories.

Purpose

Returns the distinct nonempty prompt categories stored in the authoritative Prompts table for use by category selectors and Prompt Engineering filters.

Parameters:

Name Type Description Default
db_path str

Path to the application SQLite database.

required

Returns:

Type Description
List[str]

List[str]: Distinct prompt categories ordered without regard to case.

Raises:

Type Description
Error

Raised when prompt categories cannot be retrieved.

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

	Purpose:
	    Returns the distinct nonempty prompt categories stored in the authoritative Prompts
	    table for use by category selectors and Prompt Engineering filters.

	Args:
	    db_path (str): Path to the application SQLite database.

	Returns:
	    List[str]: Distinct prompt categories ordered without regard to case.

	Raises:
	    Error: Raised when prompt categories cannot be retrieved.
	"""
	try:
		throw_if( 'db_path', db_path )

		with sqlite3.connect( db_path ) as conn:
			rows = conn.execute( '''
                                 SELECT DISTINCT TRIM("Category")
                                 FROM "Prompts"
                                 WHERE TRIM(COALESCE("Category", '')) <> ''
                                 ORDER BY TRIM("Category") COLLATE NOCASE;
			                     ''' ).fetchall( )

		return [ str( row[ 0 ] ).strip( ) for row in rows if
			row and str( row[ 0 ] or '' ).strip( ) ]

	except Exception as e:
		exception = Error( e )
		exception.module = 'app'
		exception.cause = 'fetch_prompt_categories'
		exception.method = ('fetch_prompt_categories( db_path: str ) -> List[ str ]')
		Logger( ).write( exception )
		raise exception

fetch_prompts_by_category

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

Retrieve prompts for one category.

Purpose

Returns prompt records assigned to the selected category. Category comparison is case-insensitive and ignores surrounding whitespace.

Parameters:

Name Type Description Default
db_path str

Path to the application SQLite database.

required
category str

Prompt category used to restrict the returned records.

required

Returns:

Type Description
List[Dict[str, Any]]

List[Dict[str, Any]]: Matching prompt records ordered by Title, Name, and ID.

Raises:

Type Description
Error

Raised when prompts cannot be retrieved for the selected category.

Source code in app.py
def fetch_prompts_by_category( db_path: str, category: str ) -> List[ Dict[ str, Any ] ]:
	"""Retrieve prompts for one category.

	Purpose:
	    Returns prompt records assigned to the selected category. Category comparison is
	    case-insensitive and ignores surrounding whitespace.

	Args:
	    db_path (str): Path to the application SQLite database.
	    category (str): Prompt category used to restrict the returned records.

	Returns:
	    List[Dict[str, Any]]: Matching prompt records ordered by Title, Name, and ID.

	Raises:
	    Error: Raised when prompts cannot be retrieved for the selected category.
	"""
	try:
		throw_if( 'db_path', db_path )

		selected_category = str( category or '' ).strip( )

		if not selected_category:
			return [ ]

		with sqlite3.connect( db_path ) as conn:
			conn.row_factory = sqlite3.Row

			rows = conn.execute( '''
                                 SELECT "ID",
                                        "Title",
                                        "Name",
                                        "Category",
                                        "Text"
                                 FROM "Prompts"
                                 WHERE TRIM(COALESCE("Category", '')) = ?
                                     COLLATE NOCASE
                                 ORDER BY COALESCE(NULLIF(TRIM("Title"), ''), "Name")
                                              COLLATE NOCASE,
                                          "ID";
			                     ''', (selected_category,) ).fetchall( )

		return [ { 'ID': int( row[ 'ID' ] ), 'Title': str( row[ 'Title' ] or '' ).strip( ),
			'Name': str( row[ 'Name' ] or '' ).strip( ),
			'Category': str( row[ 'Category' ] or '' ).strip( ),
			'Text': str( row[ 'Text' ] or '' ), } for row in rows ]

	except Exception as e:
		exception = Error( e )
		exception.module = 'app'
		exception.cause = 'fetch_prompts_by_category'
		exception.method = ('fetch_prompts_by_category( db_path: str, category: str ) '
		                    '-> List[ Dict[ str, Any ] ]')
		Logger( ).write( exception )
		raise exception

fetch_prompt_titles

fetch_prompt_titles(
    db_path: str, categories: Optional[List[str]] = None
) -> List[Tuple[int, str]]

Retrieve prompt identifiers and display titles.

Purpose

Returns stable integer prompt identifiers paired with user-facing labels. Title is used first, followed by Name and then a generated ID label.

Parameters:

Name Type Description Default
db_path str

Path to the application SQLite database.

required
categories Optional[List[str]]

Categories used to restrict the returned prompts.

None

Returns:

Type Description
List[Tuple[int, str]]

List[Tuple[int, str]]: Prompt identifiers paired with display labels.

Raises:

Type Description
Error

Raised when prompt identifiers and titles cannot be retrieved.

Source code in app.py
def fetch_prompt_titles( db_path: str,
	categories: Optional[ List[ str ] ] = None ) -> List[ Tuple[ int, str ] ]:
	"""Retrieve prompt identifiers and display titles.

	Purpose:
	    Returns stable integer prompt identifiers paired with user-facing labels. Title is used
	    first, followed by Name and then a generated ID label.

	Args:
	    db_path (str): Path to the application SQLite database.
	    categories (Optional[List[str]]): Categories used to restrict the returned prompts.

	Returns:
	    List[Tuple[int, str]]: Prompt identifiers paired with display labels.

	Raises:
	    Error: Raised when prompt identifiers and titles cannot be retrieved.
	"""
	try:
		records = fetch_prompt_records( db_path=db_path, categories=categories )

		return [ (int( record[ 'ID' ] ),
			str( record[ 'Title' ] or record[ 'Name' ] or f"Prompt {record[ 'ID' ]}" ).strip( ))
			for
			record in records ]

	except Exception as e:
		exception = Error( e )
		exception.module = 'app'
		exception.cause = 'fetch_prompt_titles'
		exception.method = ('fetch_prompt_titles( db_path: str, '
		                    'categories: Optional[ List[ str ] ] = None ) '
		                    '-> List[ Tuple[ int, str ] ]')
		Logger( ).write( exception )
		raise exception

fetch_prompt_names

fetch_prompt_names(
    db_path: str, categories: Optional[List[str]] = None
) -> List[str]

Retrieve user-facing prompt titles.

Purpose

Preserves compatibility with the current legacy System Instructions selectors while reading Title values from the authoritative Prompts schema.

Parameters:

Name Type Description Default
db_path str

Path to the application SQLite database.

required
categories Optional[List[str]]

Categories used to restrict the returned prompts.

None

Returns:

Type Description
List[str]

List[str]: Nonempty user-facing prompt titles.

Raises:

Type Description
Error

Raised when prompt titles cannot be retrieved.

Source code in app.py
def fetch_prompt_names( db_path: str, categories: Optional[ List[ str ] ] = None ) -> List[ str ]:
	"""Retrieve user-facing prompt titles.

	Purpose:
	    Preserves compatibility with the current legacy System Instructions selectors while
	    reading Title values from the authoritative Prompts schema.

	Args:
	    db_path (str): Path to the application SQLite database.
	    categories (Optional[List[str]]): Categories used to restrict the returned prompts.

	Returns:
	    List[str]: Nonempty user-facing prompt titles.

	Raises:
	    Error: Raised when prompt titles cannot be retrieved.
	"""
	try:
		records = fetch_prompt_records( db_path=db_path, categories=categories )

		return [ str( record.get( 'Title' ) or record.get(
			'Name' ) or f"Prompt {record.get( 'ID' )}" ).strip( ) for record in records if str(
			record.get( 'Title' ) or record.get(
				'Name' ) or f"Prompt {record.get( 'ID' )}" ).strip( ) ]

	except Exception as e:
		exception = Error( e )
		exception.module = 'app'
		exception.cause = 'fetch_prompt_names'
		exception.method = ('fetch_prompt_names( db_path: str, '
		                    'categories: Optional[ List[ str ] ] = None ) '
		                    '-> List[ str ]')
		Logger( ).write( exception )
		raise exception

fetch_prompt_text

fetch_prompt_text(
    db_path: str, prompt_reference: Any
) -> Optional[str]

Retrieve prompt text.

Purpose

Retrieves prompt text by stable integer ID while retaining temporary compatibility with existing selectors that submit a Title or Name string.

Parameters:

Name Type Description Default
db_path str

Path to the application SQLite database.

required
prompt_reference Any

Prompt ID, Title, or Name used to locate the record.

required

Returns:

Type Description
Optional[str]

Optional[str]: Prompt text when a matching record exists; otherwise, None.

Raises:

Type Description
Error

Raised when prompt text cannot be retrieved.

Source code in app.py
def fetch_prompt_text( db_path: str, prompt_reference: Any ) -> Optional[ str ]:
	"""Retrieve prompt text.

	Purpose:
	    Retrieves prompt text by stable integer ID while retaining temporary compatibility with
	    existing selectors that submit a Title or Name string.

	Args:
	    db_path (str): Path to the application SQLite database.
	    prompt_reference (Any): Prompt ID, Title, or Name used to locate the record.

	Returns:
	    Optional[str]: Prompt text when a matching record exists; otherwise, None.

	Raises:
	    Error: Raised when prompt text cannot be retrieved.
	"""
	try:
		throw_if( 'db_path', db_path )

		if prompt_reference is None:
			return None

		row: Optional[ Tuple[ Any, ... ] ] = None

		with sqlite3.connect( db_path ) as conn:
			if isinstance( prompt_reference, int ):
				row = conn.execute( '''
                                    SELECT "Text"
                                    FROM "Prompts"
                                    WHERE "ID" = ?;
				                    ''', (prompt_reference,) ).fetchone( )

			else:
				reference_text = str( prompt_reference ).strip( )

				if not reference_text:
					return None

				try:
					prompt_id = int( reference_text )
				except ValueError:
					prompt_id = None

				if prompt_id is not None:
					row = conn.execute( '''
                                        SELECT "Text"
                                        FROM "Prompts"
                                        WHERE "ID" = ?;
					                    ''', (prompt_id,) ).fetchone( )

				else:
					row = conn.execute( '''
                                        SELECT "Text"
                                        FROM "Prompts"
                                        WHERE TRIM(COALESCE("Title", '')) = ?
                                            COLLATE NOCASE
                                           OR TRIM(COALESCE("Name", '')) = ?
                                            COLLATE NOCASE
                                        ORDER BY CASE
                                                     WHEN TRIM(COALESCE("Title", '')) = ?
                                                         COLLATE NOCASE
                                                         THEN 0
                                                     ELSE 1
                                                     END,
                                                 "ID" LIMIT 1;
					                    ''',
						(reference_text, reference_text, reference_text,) ).fetchone( )

		if not row or row[ 0 ] is None:
			return None

		return str( row[ 0 ] )

	except Exception as e:
		exception = Error( e )
		exception.module = 'app'
		exception.cause = 'fetch_prompt_text'
		exception.method = ('fetch_prompt_text( db_path: str, prompt_reference: Any ) '
		                    '-> Optional[ str ]')
		Logger( ).write( exception )
		raise exception

fetch_prompts_df

fetch_prompts_df() -> pd.DataFrame

Retrieve prompts as a DataFrame.

Purpose

Returns all prompt records using the authoritative Prompts schema and adds the Boolean selection column used by the Prompt Engineering interface.

Returns:

Type Description
DataFrame

pd.DataFrame: Prompt records containing Selected, ID, Title, Name, Category, and Text.

Raises:

Type Description
Error

Raised when the prompt DataFrame cannot be created.

Source code in app.py
def fetch_prompts_df( ) -> pd.DataFrame:
	"""Retrieve prompts as a DataFrame.

	Purpose:
	    Returns all prompt records using the authoritative Prompts schema and adds the Boolean
	    selection column used by the Prompt Engineering interface.

	Returns:
	    pd.DataFrame: Prompt records containing Selected, ID, Title, Name, Category, and Text.

	Raises:
	    Error: Raised when the prompt DataFrame cannot be created.
	"""
	try:
		with sqlite3.connect( cfg.DB_PATH ) as conn:
			df_prompts = pd.read_sql_query( '''
                                            SELECT "ID",
                                                   "Title",
                                                   "Name",
                                                   "Category",
                                                   "Text"
                                            FROM "Prompts"
                                            ORDER BY "ID" DESC;
			                                ''', conn )

		df_prompts.insert( 0, 'Selected', False )
		return df_prompts

	except Exception as e:
		exception = Error( e )
		exception.module = 'app'
		exception.cause = 'fetch_prompts_df'
		exception.method = 'fetch_prompts_df( ) -> pd.DataFrame'
		Logger( ).write( exception )
		raise exception

fetch_prompt_by_id

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

Retrieve one prompt by ID.

Purpose

Reads one prompt record using its stable integer primary-key identifier.

Parameters:

Name Type Description Default
prompt_id int

Prompt primary-key identifier.

required

Returns:

Type Description
Optional[Dict[str, Any]]

Optional[Dict[str, Any]]: Prompt record when found; otherwise, None.

Raises:

Type Description
Error

Raised when the prompt record cannot be retrieved.

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

	Purpose:
	    Reads one prompt record using its stable integer primary-key identifier.

	Args:
	    prompt_id (int): Prompt primary-key identifier.

	Returns:
	    Optional[Dict[str, Any]]: Prompt record when found; otherwise, None.

	Raises:
	    Error: Raised when the prompt record cannot be retrieved.
	"""
	try:
		if prompt_id is None:
			return None

		selected_id = int( prompt_id )

		if selected_id <= 0:
			return None

		with sqlite3.connect( cfg.DB_PATH ) as conn:
			conn.row_factory = sqlite3.Row

			row = conn.execute( '''
                                SELECT "ID",
                                       "Title",
                                       "Name",
                                       "Category",
                                       "Text"
                                FROM "Prompts"
                                WHERE "ID" = ?;
			                    ''', (selected_id,) ).fetchone( )

		if row is None:
			return None

		return { 'ID': int( row[ 'ID' ] ), 'Title': str( row[ 'Title' ] or '' ).strip( ),
			'Name': str( row[ 'Name' ] or '' ).strip( ),
			'Category': str( row[ 'Category' ] or '' ).strip( ),
			'Text': str( row[ 'Text' ] or '' ), }

	except Exception as e:
		exception = Error( e )
		exception.module = 'app'
		exception.cause = 'fetch_prompt_by_id'
		exception.method = ('fetch_prompt_by_id( prompt_id: int ) '
		                    '-> Optional[ Dict[ str, Any ] ]')
		Logger( ).write( exception )
		raise exception

fetch_prompt_by_name

fetch_prompt_by_name(name: str) -> Optional[Dict[str, Any]]

Retrieve one prompt by Title or Name.

Purpose

Preserves temporary compatibility with legacy Gipity callers that identify prompts using display text instead of the stable integer primary key.

Parameters:

Name Type Description Default
name str

Prompt Title or Name used to locate the record.

required

Returns:

Type Description
Optional[Dict[str, Any]]

Optional[Dict[str, Any]]: First matching prompt record; otherwise, None.

Raises:

Type Description
Error

Raised when the prompt record cannot be retrieved.

Source code in app.py
def fetch_prompt_by_name( name: str ) -> Optional[ Dict[ str, Any ] ]:
	"""Retrieve one prompt by Title or Name.

	Purpose:
	    Preserves temporary compatibility with legacy Gipity callers that identify prompts using
	    display text instead of the stable integer primary key.

	Args:
	    name (str): Prompt Title or Name used to locate the record.

	Returns:
	    Optional[Dict[str, Any]]: First matching prompt record; otherwise, None.

	Raises:
	    Error: Raised when the prompt record cannot be retrieved.
	"""
	try:
		selected_name = str( name or '' ).strip( )

		if not selected_name:
			return None

		with sqlite3.connect( cfg.DB_PATH ) as conn:
			conn.row_factory = sqlite3.Row

			row = conn.execute( '''
                                SELECT "ID",
                                       "Title",
                                       "Name",
                                       "Category",
                                       "Text"
                                FROM "Prompts"
                                WHERE TRIM(COALESCE("Title", '')) = ?
                                    COLLATE NOCASE
                                   OR TRIM(COALESCE("Name", '')) = ?
                                    COLLATE NOCASE
                                ORDER BY CASE
                                             WHEN TRIM(COALESCE("Title", '')) = ?
                                                 COLLATE NOCASE
                                                 THEN 0
                                             ELSE 1
                                             END,
                                         "ID" LIMIT 1;
			                    ''', (selected_name, selected_name, selected_name,) ).fetchone( )

		if row is None:
			return None

		return { 'ID': int( row[ 'ID' ] ), 'Title': str( row[ 'Title' ] or '' ).strip( ),
			'Name': str( row[ 'Name' ] or '' ).strip( ),
			'Category': str( row[ 'Category' ] or '' ).strip( ),
			'Text': str( row[ 'Text' ] or '' ), }

	except Exception as e:
		exception = Error( e )
		exception.module = 'app'
		exception.cause = 'fetch_prompt_by_name'
		exception.method = ('fetch_prompt_by_name( name: str ) '
		                    '-> Optional[ Dict[ str, Any ] ]')
		Logger( ).write( exception )
		raise exception

insert_prompt

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

Insert a prompt record.

Purpose

Creates a prompt using the authoritative Title, Name, Category, and Text fields and returns the generated integer primary-key identifier.

Parameters:

Name Type Description Default
data Dict[str, Any]

Prompt values containing Title, Name, Category, and Text.

required

Returns:

Name Type Description
int int

Integer ID assigned to the inserted prompt record.

Raises:

Type Description
Error

Raised when the prompt record cannot be inserted.

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

	Purpose:
	    Creates a prompt using the authoritative Title, Name, Category, and Text fields and
	    returns the generated integer primary-key identifier.

	Args:
	    data (Dict[str, Any]): Prompt values containing Title, Name, Category, and Text.

	Returns:
	    int: Integer ID assigned to the inserted prompt record.

	Raises:
	    Error: Raised when the prompt record cannot be inserted.
	"""
	try:
		throw_if( 'data', data )

		title = str( data.get( 'Title', '' ) or '' ).strip( )
		name = str( data.get( 'Name', '' ) or '' ).strip( )
		category = str( data.get( 'Category', '' ) or '' ).strip( )
		text = str( data.get( 'Text', '' ) or '' )

		if not title and not name:
			raise ValueError( 'Title or Name is required before creating a prompt.' )

		with sqlite3.connect( cfg.DB_PATH ) as conn:
			cursor = conn.execute( '''
                                   INSERT INTO "Prompts"
                                   ("Title",
                                    "Name",
                                    "Category",
                                    "Text")
                                   VALUES (?, ?, ?, ?);
			                       ''', (title, name, category, text,) )

			conn.commit( )
			prompt_id = int( cursor.lastrowid )

		return prompt_id

	except Exception as e:
		exception = Error( e )
		exception.module = 'app'
		exception.cause = 'insert_prompt'
		exception.method = ('insert_prompt( data: Dict[ str, Any ] ) -> int')
		Logger( ).write( exception )
		raise exception

update_prompt

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

Update a prompt record.

Purpose

Updates the authoritative Title, Name, Category, and Text values for one prompt identified by its stable integer primary key.

Parameters:

Name Type Description Default
prompt_id int

Prompt primary-key identifier.

required
data Dict[str, Any]

Updated Title, Name, Category, and Text values.

required

Returns:

Name Type Description
None None

The function updates the persistent prompt record.

Raises:

Type Description
Error

Raised when the prompt record cannot be updated.

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

	Purpose:
	    Updates the authoritative Title, Name, Category, and Text values for one prompt
	    identified by its stable integer primary key.

	Args:
	    prompt_id (int): Prompt primary-key identifier.
	    data (Dict[str, Any]): Updated Title, Name, Category, and Text values.

	Returns:
	    None: The function updates the persistent prompt record.

	Raises:
	    Error: Raised when the prompt record cannot be updated.
	"""
	try:
		throw_if( 'data', data )

		selected_id = int( prompt_id )

		if selected_id <= 0:
			raise ValueError( 'Prompt ID must be greater than zero.' )

		title = str( data.get( 'Title', '' ) or '' ).strip( )
		name = str( data.get( 'Name', '' ) or '' ).strip( )
		category = str( data.get( 'Category', '' ) or '' ).strip( )
		text = str( data.get( 'Text', '' ) or '' )

		if not title and not name:
			raise ValueError( 'Title or Name is required before updating a prompt.' )

		with sqlite3.connect( cfg.DB_PATH ) as conn:
			cursor = conn.execute( '''
                                   UPDATE "Prompts"
                                   SET "Title"    = ?,
                                       "Name"     = ?,
                                       "Category" = ?,
                                       "Text"     = ?
                                   WHERE "ID" = ?;
			                       ''', (title, name, category, text, selected_id,) )

			if cursor.rowcount == 0:
				raise ValueError( f'Prompt ID {selected_id} was not found.' )

			conn.commit( )

	except Exception as e:
		exception = Error( e )
		exception.module = 'app'
		exception.cause = 'update_prompt'
		exception.method = ('update_prompt( prompt_id: int, '
		                    'data: Dict[ str, Any ] ) -> None')
		Logger( ).write( exception )
		raise exception

delete_prompt

delete_prompt(prompt_id: int) -> None

Delete a prompt record.

Purpose

Removes one prompt from the authoritative Prompts table using its stable integer primary-key identifier.

Parameters:

Name Type Description Default
prompt_id int

Prompt primary-key identifier.

required

Returns:

Name Type Description
None None

The function removes the persistent prompt record.

Raises:

Type Description
Error

Raised when the prompt record cannot be deleted.

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

	Purpose:
	    Removes one prompt from the authoritative Prompts table using its stable integer
	    primary-key identifier.

	Args:
	    prompt_id (int): Prompt primary-key identifier.

	Returns:
	    None: The function removes the persistent prompt record.

	Raises:
	    Error: Raised when the prompt record cannot be deleted.
	"""
	try:
		selected_id = int( prompt_id )

		if selected_id <= 0:
			raise ValueError( 'Prompt ID must be greater than zero.' )

		with sqlite3.connect( cfg.DB_PATH ) as conn:
			cursor = conn.execute( '''
                                   DELETE
                                   FROM "Prompts"
                                   WHERE "ID" = ?;
			                       ''', (selected_id,) )

			if cursor.rowcount == 0:
				raise ValueError( f'Prompt ID {selected_id} was not found.' )

			conn.commit( )

	except Exception as e:
		exception = Error( e )
		exception.module = 'app'
		exception.cause = 'delete_prompt'
		exception.method = ('delete_prompt( prompt_id: int ) -> None')
		Logger( ).write( exception )
		raise exception

format_prompt_option

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

Format a prompt selector option.

Purpose

Converts a stable prompt identifier into its user-facing Title. Name and the prompt identifier are used as fallbacks when Title is empty.

Parameters:

Name Type Description Default
prompt_id int

Prompt primary-key identifier.

required
prompt_lookup Dict[int, Dict[str, Any]]

Prompt records indexed by integer ID.

required

Returns:

Name Type Description
str str

User-facing prompt selector label.

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

	Purpose:
	    Converts a stable prompt identifier into its user-facing Title. Name and the prompt
	    identifier are used as fallbacks when Title is empty.

	Args:
	    prompt_id (int): Prompt primary-key identifier.
	    prompt_lookup (Dict[int, Dict[str, Any]]): Prompt records indexed by integer ID.

	Returns:
	    str: User-facing prompt selector label.
	"""
	record = prompt_lookup.get( int( prompt_id ), { } )

	title = str( record.get( 'Title', '' ) or '' ).strip( )

	if title:
		return title

	name = str( record.get( 'Name', '' ) or '' ).strip( )

	if name:
		return name

	return f'Prompt {prompt_id}'

normalize_prompt_category

normalize_prompt_category(category: str) -> str

Normalize a prompt category.

Purpose

Converts a prompt category into a stable comparison value by removing surrounding whitespace, collapsing internal whitespace, normalizing ampersands, and converting text to lowercase.

Parameters:

Name Type Description Default
category str

Prompt category to normalize.

required

Returns:

Name Type Description
str str

Normalized prompt-category value.

Source code in app.py
def normalize_prompt_category( category: str ) -> str:
	"""Normalize a prompt category.

	Purpose:
	    Converts a prompt category into a stable comparison value by removing surrounding
	    whitespace, collapsing internal whitespace, normalizing ampersands, and converting
	    text to lowercase.

	Args:
	    category (str): Prompt category to normalize.

	Returns:
	    str: Normalized prompt-category value.
	"""
	if not isinstance( category, str ):
		return ''

	normalized = category.strip( )

	if not normalized:
		return ''

	normalized = normalized.replace( '&', ' and ' )
	normalized = normalized.replace( '_', ' ' )
	normalized = normalized.replace( '-', ' ' )
	normalized = re.sub( r'\s+', ' ', normalized )
	normalized = normalized.lower( ).strip( )

	return normalized

get_prompt_category_aliases

get_prompt_category_aliases(
    category: str,
) -> Tuple[str, ...]

Return accepted aliases for a prompt category.

Purpose

Provides explicit normalized aliases for known category-label variations without permitting unrestricted substring matching between unrelated categories.

Parameters:

Name Type Description Default
category str

Canonical prompt category.

required

Returns:

Type Description
Tuple[str, ...]

Tuple[str, ...]: Normalized canonical category and recognized aliases.

Source code in app.py
def get_prompt_category_aliases( category: str ) -> Tuple[ str, ... ]:
	"""Return accepted aliases for a prompt category.

	Purpose:
	    Provides explicit normalized aliases for known category-label variations without
	    permitting unrestricted substring matching between unrelated categories.

	Args:
	    category (str): Canonical prompt category.

	Returns:
	    Tuple[str, ...]: Normalized canonical category and recognized aliases.
	"""
	normalized_category = normalize_prompt_category( category )

	alias_map: Dict[ str, Tuple[ str, ... ] ] = {
		normalize_prompt_category( 'Research / Academic' ): (
			normalize_prompt_category( 'Research / Academic' ),
			normalize_prompt_category( 'Research and Academic' ),
			normalize_prompt_category( 'Academic Research' ),),
		normalize_prompt_category( 'Prompt Engineering' ): (
			normalize_prompt_category( 'Prompt Engineering' ),
			normalize_prompt_category( 'Prompt Design' ),),
		normalize_prompt_category( 'Writing / Administrative' ): (
			normalize_prompt_category( 'Writing / Administrative' ),
			normalize_prompt_category( 'Writing and Administrative' ),
			normalize_prompt_category( 'Administrative Writing' ),),
		normalize_prompt_category( 'Compliance / Legal / Budget' ): (
			normalize_prompt_category( 'Compliance / Legal / Budget' ),
			normalize_prompt_category( 'Compliance Legal Budget' ),
			normalize_prompt_category( 'Compliance and Legal and Budget' ),),
		normalize_prompt_category( 'Image Generation' ): (
			normalize_prompt_category( 'Image Generation' ),
			normalize_prompt_category( 'Generate Images' ),),
		normalize_prompt_category( 'Business / Finance / Marketing' ): (
			normalize_prompt_category( 'Business / Finance / Marketing' ),
			normalize_prompt_category( 'Business Finance Marketing' ),
			normalize_prompt_category( 'Business and Finance and Marketing' ),),
		normalize_prompt_category( 'Software Engineering' ): (
			normalize_prompt_category( 'Software Engineering' ),
			normalize_prompt_category( 'Programming' ),
			normalize_prompt_category( 'Software Development' ),),
		normalize_prompt_category( 'Data Analytics & Governance' ): (
			normalize_prompt_category( 'Data Analytics & Governance' ),
			normalize_prompt_category( 'Data Analytics and Governance' ),
			normalize_prompt_category( 'Analytics and Data Governance' ),),
		normalize_prompt_category( 'Instruction/ Training / Planning' ): (
			normalize_prompt_category( 'Instruction/ Training / Planning' ),
			normalize_prompt_category( 'Instruction / Training / Planning' ),
			normalize_prompt_category( 'Instruction Training Planning' ),),
		normalize_prompt_category( 'Translation API' ): (
			normalize_prompt_category( 'Translation API' ),
			normalize_prompt_category( 'Translation' ),),
		normalize_prompt_category( 'Transcription API' ): (
			normalize_prompt_category( 'Transcription API' ),
			normalize_prompt_category( 'Transcription' ),),
		normalize_prompt_category( 'Speech API' ): (normalize_prompt_category( 'Speech API' ),
			normalize_prompt_category( 'Text To Speech' ),
			normalize_prompt_category( 'Text-to-Speech' ), normalize_prompt_category( 'TTS' ),),
		normalize_prompt_category( 'Image Analysis' ): (
			normalize_prompt_category( 'Image Analysis' ),
			normalize_prompt_category( 'Image Understanding' ),
			normalize_prompt_category( 'Vision Analysis' ),),
		normalize_prompt_category( 'Image Editing' ): (normalize_prompt_category( 'Image '
		                                                                          'Editing' ),
			normalize_prompt_category( 'Edit Images' ),
			normalize_prompt_category( 'Image Modification' ),), }

	if normalized_category in alias_map:
		return alias_map[ normalized_category ]

	if normalized_category:
		return (normalized_category,)

	return tuple( )

prompt_category_matches_policy

prompt_category_matches_policy(
    category: str, allowed_categories: Tuple[str, ...]
) -> bool

Determine whether a prompt category is allowed.

Purpose

Compares a database category with the canonical categories permitted by one Gipity mode. Matching uses normalized exact values and explicit aliases only.

Parameters:

Name Type Description Default
category str

Database prompt category.

required
allowed_categories Tuple[str, ...]

Categories permitted by the current mode.

required

Returns:

Name Type Description
bool bool

True when the database category is permitted; otherwise, False.

Source code in app.py
def prompt_category_matches_policy( category: str, allowed_categories: Tuple[ str, ... ] ) -> bool:
	"""Determine whether a prompt category is allowed.

	Purpose:
	    Compares a database category with the canonical categories permitted by one Gipity
	    mode. Matching uses normalized exact values and explicit aliases only.

	Args:
	    category (str): Database prompt category.
	    allowed_categories (Tuple[str, ...]): Categories permitted by the current mode.

	Returns:
	    bool: True when the database category is permitted; otherwise, False.
	"""
	normalized_category = normalize_prompt_category( category )

	if not normalized_category:
		return False

	if not isinstance( allowed_categories, tuple ):
		return False

	for allowed_category in allowed_categories:
		aliases = get_prompt_category_aliases( allowed_category )

		if normalized_category in aliases:
			return True

	return False

filter_prompt_categories

filter_prompt_categories(
    available_categories: List[str],
    allowed_categories: Tuple[str, ...],
) -> List[str]

Filter prompt categories for one mode.

Purpose

Restricts database categories to those allowed by the current mode while preserving their exact database labels and stable display order.

Parameters:

Name Type Description Default
available_categories List[str]

Categories read from the Prompts table.

required
allowed_categories Tuple[str, ...]

Categories permitted by the current mode.

required

Returns:

Type Description
List[str]

List[str]: Allowed database categories ordered according to the mode policy.

Source code in app.py
def filter_prompt_categories( available_categories: List[ str ],
	allowed_categories: Tuple[ str, ... ] ) -> List[ str ]:
	"""Filter prompt categories for one mode.

	Purpose:
	    Restricts database categories to those allowed by the current mode while preserving
	    their exact database labels and stable display order.

	Args:
	    available_categories (List[str]): Categories read from the Prompts table.
	    allowed_categories (Tuple[str, ...]): Categories permitted by the current mode.

	Returns:
	    List[str]: Allowed database categories ordered according to the mode policy.
	"""
	if not isinstance( available_categories, list ):
		return [ ]

	if not isinstance( allowed_categories, tuple ):
		return [ ]

	filtered_categories: List[ str ] = [ ]

	for allowed_category in allowed_categories:
		allowed_aliases = get_prompt_category_aliases( allowed_category )

		for available_category in available_categories:
			if not isinstance( available_category, str ):
				continue

			category_value = available_category.strip( )

			if not category_value:
				continue

			normalized_available = normalize_prompt_category( category_value )

			if normalized_available not in allowed_aliases:
				continue

			if category_value in filtered_categories:
				continue

			filtered_categories.append( category_value )

	return filtered_categories

load_prompt_into_state

load_prompt_into_state(
    prompt_id_key: str, instruction_key: str
) -> None

Load a selected prompt into session state.

Purpose

Retrieves the prompt selected through a mode-specific prompt selector and copies its Text value into the corresponding editable system-instruction control.

Parameters:

Name Type Description Default
prompt_id_key str

Session-state key containing the selected prompt ID.

required
instruction_key str

Session-state key receiving the selected prompt text.

required

Returns:

Name Type Description
None None

The function updates Streamlit session state.

Raises:

Type Description
Error

Raised when the supplied state keys are invalid or the selected prompt cannot be retrieved.

Source code in app.py
def load_prompt_into_state( prompt_id_key: str, instruction_key: str ) -> None:
	"""Load a selected prompt into session state.

	Purpose:
	    Retrieves the prompt selected through a mode-specific prompt selector and copies its
	    Text value into the corresponding editable system-instruction control.

	Args:
	    prompt_id_key (str): Session-state key containing the selected prompt ID.
	    instruction_key (str): Session-state key receiving the selected prompt text.

	Returns:
	    None: The function updates Streamlit session state.

	Raises:
	    Error: Raised when the supplied state keys are invalid or the selected prompt cannot
	        be retrieved.
	"""
	try:
		throw_if( 'prompt_id_key', prompt_id_key )
		throw_if( 'instruction_key', instruction_key )

		selected_prompt_id = st.session_state.get( prompt_id_key, None )

		if selected_prompt_id in (None, ''):
			st.session_state[ instruction_key ] = ''
			return

		try:
			prompt_id = int( selected_prompt_id )
		except (TypeError, ValueError) as e:
			raise ValueError( f'The selected prompt ID is invalid: {selected_prompt_id}' ) from e

		if prompt_id <= 0:
			raise ValueError( 'The selected prompt ID must be greater than zero.' )

		prompt_record = fetch_prompt_by_id( prompt_id )

		if prompt_record is None:
			raise ValueError( f'Prompt ID {prompt_id} was not found.' )

		prompt_text = prompt_record.get( 'Text', '' )

		st.session_state[ instruction_key ] = str( prompt_text or '' )

	except Exception as e:
		exception = Error( e )
		exception.module = 'app'
		exception.cause = 'load_prompt_into_state'
		exception.method = ('load_prompt_into_state( '
		                    'prompt_id_key: str, instruction_key: str ) -> None')
		Logger( ).write( exception )
		raise exception

clear_prompt_state

clear_prompt_state(
    category_key: str,
    prompt_id_key: str,
    instruction_key: str,
) -> None

Clear one mode's system-prompt state.

Purpose

Clears the selected category, selected prompt ID, and editable instruction text for one application mode without modifying any record in the Prompts table.

Parameters:

Name Type Description Default
category_key str

Session-state key containing the selected prompt category.

required
prompt_id_key str

Session-state key containing the selected prompt ID.

required
instruction_key str

Session-state key containing the editable instruction text.

required

Returns:

Name Type Description
None None

The function updates Streamlit session state.

Raises:

Type Description
Error

Raised when the supplied state keys are invalid or cannot be cleared.

Source code in app.py
def clear_prompt_state( category_key: str, prompt_id_key: str, instruction_key: str ) -> None:
	"""Clear one mode's system-prompt state.

	Purpose:
	    Clears the selected category, selected prompt ID, and editable instruction text for
	    one application mode without modifying any record in the Prompts table.

	Args:
	    category_key (str): Session-state key containing the selected prompt category.
	    prompt_id_key (str): Session-state key containing the selected prompt ID.
	    instruction_key (str): Session-state key containing the editable instruction text.

	Returns:
	    None: The function updates Streamlit session state.

	Raises:
	    Error: Raised when the supplied state keys are invalid or cannot be cleared.
	"""
	try:
		throw_if( 'category_key', category_key )
		throw_if( 'prompt_id_key', prompt_id_key )
		throw_if( 'instruction_key', instruction_key )

		st.session_state[ category_key ] = None
		st.session_state[ prompt_id_key ] = None
		st.session_state[ instruction_key ] = ''

	except Exception as e:
		exception = Error( e )
		exception.module = 'app'
		exception.cause = 'clear_prompt_state'
		exception.method = ('clear_prompt_state( category_key: str, '
		                    'prompt_id_key: str, instruction_key: str ) -> None')
		Logger( ).write( exception )
		raise exception

convert_prompt_state

convert_prompt_state(instruction_key: str) -> None

Convert mode-specific system instructions.

Purpose

Converts the specified instruction value between supported XML prompt blocks and Markdown or HTML heading notation using Gipity's existing conversion helpers.

Parameters:

Name Type Description Default
instruction_key str

Session-state key containing the editable instruction text.

required

Returns:

Name Type Description
None None

The function updates Streamlit session state.

Raises:

Type Description
Error

Raised when the supplied state key is invalid or the instruction text cannot be converted.

Source code in app.py
def convert_prompt_state( instruction_key: str ) -> None:
	"""Convert mode-specific system instructions.

	Purpose:
	    Converts the specified instruction value between supported XML prompt blocks and
	    Markdown or HTML heading notation using Gipity's existing conversion helpers.

	Args:
	    instruction_key (str): Session-state key containing the editable instruction text.

	Returns:
	    None: The function updates Streamlit session state.

	Raises:
	    Error: Raised when the supplied state key is invalid or the instruction text cannot
	        be converted.
	"""
	try:
		throw_if( 'instruction_key', instruction_key )

		instruction_text = st.session_state.get( instruction_key, '' )

		if instruction_text is None:
			st.session_state[ instruction_key ] = ''
			return

		if not isinstance( instruction_text, str ):
			instruction_text = str( instruction_text )

		source_text = instruction_text.strip( )

		if not source_text:
			return

		if cfg.XML_BLOCK_PATTERN.search( source_text ):
			converted_text = convert_xml( source_text )
		else:
			converted_text = convert_markdown( source_text )

		st.session_state[ instruction_key ] = str( converted_text or '' )

	except Exception as e:
		exception = Error( e )
		exception.module = 'app'
		exception.cause = 'convert_prompt_state'
		exception.method = ('convert_prompt_state( instruction_key: str ) -> None')
		Logger( ).write( exception )
		raise exception

render_system_prompt_expander

render_system_prompt_expander(
    state_prefix: str,
    instruction_key: str,
    allowed_categories: Tuple[str, ...],
    label: str = "System Instructions",
    height: int = 135,
) -> None

Render a category-driven system-instruction expander.

Purpose

Renders a reusable System Instructions interface containing an editable instruction area, mode-filtered category selector, prompt selector, clear control, and XML or Markdown conversion control. Prompt selection uses the stable integer ID stored in the authoritative Prompts table.

Parameters:

Name Type Description Default
state_prefix str

Prefix used to construct mode-specific widget and state keys.

required
instruction_key str

Session-state key containing the editable instruction text.

required
allowed_categories Tuple[str, ...]

Canonical prompt categories permitted by the current application mode.

required
label str

Text displayed in the Streamlit expander header.

'System Instructions'
height int

Height of the editable instruction text area in pixels.

135

Returns:

Name Type Description
None None

The function renders Streamlit controls and updates session state.

Raises:

Type Description
Error

Raised when prompt data cannot be retrieved or the expander cannot be rendered.

Source code in app.py
def render_system_prompt_expander( state_prefix: str, instruction_key: str,
	allowed_categories: Tuple[ str, ... ], label: str='System Instructions',
	height: int=135 ) -> None:
	"""Render a category-driven system-instruction expander.

	Purpose:
	    Renders a reusable System Instructions interface containing an editable instruction
	    area, mode-filtered category selector, prompt selector, clear control, and XML or
	    Markdown conversion control. Prompt selection uses the stable integer ID stored in
	    the authoritative Prompts table.

	Args:
	    state_prefix (str): Prefix used to construct mode-specific widget and state keys.
	    instruction_key (str): Session-state key containing the editable instruction text.
	    allowed_categories (Tuple[str, ...]): Canonical prompt categories permitted by the
	        current application mode.
	    label (str): Text displayed in the Streamlit expander header.
	    height (int): Height of the editable instruction text area in pixels.

	Returns:
	    None: The function renders Streamlit controls and updates session state.

	Raises:
	    Error: Raised when prompt data cannot be retrieved or the expander cannot be rendered.
	"""
	try:
		throw_if( 'state_prefix', state_prefix )
		throw_if( 'instruction_key', instruction_key )
		throw_if( 'allowed_categories', allowed_categories )
		if not isinstance( allowed_categories, tuple ):
			raise TypeError( 'allowed_categories must be a tuple of category names.' )

		try:
			text_area_height = int( height )
		except (TypeError, ValueError):
			text_area_height = 135

		if text_area_height <= 0:
			text_area_height = 135

		# ------------------------------------------------------------------
		# Mode-Specific State Contract
		# ------------------------------------------------------------------
		category_key = f'{state_prefix}_prompt_category'
		prompt_id_key = f'{state_prefix}_prompt_id'

		st.session_state.setdefault( instruction_key, '' )
		st.session_state.setdefault( category_key, None )
		st.session_state.setdefault( prompt_id_key, None )

		if st.session_state.get( category_key ) == '':
			st.session_state[ category_key ] = None

		if st.session_state.get( prompt_id_key ) == '':
			st.session_state[ prompt_id_key ] = None

		# ------------------------------------------------------------------
		# Category Repository
		# ------------------------------------------------------------------
		database_categories = fetch_prompt_categories( cfg.DB_PATH )
		mode_categories = filter_prompt_categories( available_categories=database_categories,
			allowed_categories=allowed_categories )

		selected_category = st.session_state.get( category_key, None )

		if selected_category not in mode_categories:
			st.session_state[ category_key ] = None
			st.session_state[ prompt_id_key ] = None
			selected_category = None

		# ------------------------------------------------------------------
		# Widget Callbacks
		# ------------------------------------------------------------------
		def on_category_change( ) -> None:
			"""Clear prompt state after a category change.

			Purpose:
			    Clears the selected prompt and instruction text when the user chooses a
			    different category so a prompt from the prior category cannot remain active.

			Returns:
			    None: The callback updates Streamlit session state.
			"""
			st.session_state[ prompt_id_key ] = None
			st.session_state[ instruction_key ] = ''

		def on_prompt_change( ) -> None:
			"""Load the selected prompt.

			Purpose:
			    Loads the selected prompt's Text value into the current mode's editable
			    system-instruction state.

			Returns:
			    None: The callback updates Streamlit session state.
			"""
			load_prompt_into_state( prompt_id_key=prompt_id_key, instruction_key=instruction_key )

		def on_clear( ) -> None:
			"""Clear the current mode's prompt state.

			Purpose:
			    Clears the selected category, prompt ID, and editable system instructions
			    without modifying the underlying prompt record.

			Returns:
			    None: The callback updates Streamlit session state.
			"""
			clear_prompt_state( category_key=category_key, prompt_id_key=prompt_id_key,
				instruction_key=instruction_key )

		def on_convert( ) -> None:
			"""Convert the current system instructions.

			Purpose:
			    Converts the current mode's system instructions between supported XML prompt
			    blocks and Markdown or HTML heading notation.

			Returns:
			    None: The callback updates Streamlit session state.
			"""
			convert_prompt_state( instruction_key=instruction_key )

		# ------------------------------------------------------------------
		# System Instructions Expander
		# ------------------------------------------------------------------
		with st.expander( label=label, icon='🖥️', expanded=False, width='stretch' ):
			instruction_column, selector_column = st.columns( [ 0.70, 0.30 ] )

			# --------------------------------------------------------------
			# Category and Prompt Selectors
			# --------------------------------------------------------------
			with selector_column:
				category_placeholder = 'Select Category'

				if not database_categories:
					category_placeholder = ('No Categories in Prompts')

				elif not mode_categories:
					category_placeholder = ('No Categories Match This Mode')

				st.selectbox( label='Category', options=mode_categories, index=None,
					key=category_key, on_change=on_category_change,
					placeholder=category_placeholder, disabled=not mode_categories,
					help=('Categories are read from Prompts.Category '
					      'and filtered for the current mode.'), width='stretch' )

				active_category = st.session_state.get( category_key, None )
				prompt_records: List[ Dict[ str, Any ] ] = [ ]
				if active_category:
					prompt_records = fetch_prompts_by_category( db_path=cfg.DB_PATH,
						category=str( active_category ) )

				prompt_lookup: Dict[ int, Dict[ str, Any ] ] = { int( record[ 'ID' ] ): record for
					record in prompt_records if record.get( 'ID' ) is not None }

				prompt_ids = list( prompt_lookup.keys( ) )
				selected_prompt_id = st.session_state.get( prompt_id_key, None )
				if selected_prompt_id is not None:
					try:
						selected_prompt_id = int( selected_prompt_id )
					except (TypeError, ValueError):
						selected_prompt_id = None

				if selected_prompt_id not in prompt_ids:
					st.session_state[ prompt_id_key ] = None

				if active_category and prompt_ids:
					prompt_placeholder = 'Select Prompt'

				elif active_category:
					prompt_placeholder = 'No Prompts Found'

				else:
					prompt_placeholder = 'Select Category First'

				st.selectbox( label='Prompt', options=prompt_ids,
					format_func=lambda prompt_id: format_prompt_option( prompt_id=prompt_id,
						prompt_lookup=prompt_lookup ), index=None, key=prompt_id_key,
					on_change=on_prompt_change, placeholder=prompt_placeholder,
					disabled=(not active_category or not prompt_ids),
					help=('Prompts are read from the selected category '
					      'and tracked by their stable database ID.'), width='stretch' )

			# --------------------------------------------------------------
			# Editable Instruction Text
			# --------------------------------------------------------------
			with instruction_column:
				st.text_area( label='Enter Text', height=text_area_height, width='stretch',
					help=cfg.SYSTEM_INSTRUCTIONS, key=instruction_key )

			# --------------------------------------------------------------
			# Expander Actions
			# --------------------------------------------------------------
			clear_column, convert_column = st.columns( [ 0.80, 0.20 ] )
			with clear_column:
				st.button( label='Clear Instructions', key=f'{state_prefix}_clear_instructions',
					icon='🧹', width='stretch', on_click=on_clear )

			with convert_column:
				st.button( label='XML ↔️ Markdown', key=f'{state_prefix}_convert_instructions',
					width='stretch', on_click=on_convert )

	except Exception as e:
		exception = Error( e )
		exception.module = 'app'
		exception.cause = 'render_system_prompt_expander'
		exception.method = ('render_system_prompt_expander( state_prefix: str, '
		                    'instruction_key: str, '
		                    'allowed_categories: Tuple[ str, ... ], '
		                    'label: str = \'System Instructions\', '
		                    'height: int = 135 ) -> None')
		Logger( ).write( exception )
		raise exception

build_prompt

build_prompt(user_input: str) -> str

Build prompt.

Purpose

Builds the prompt value used by the Gipity interface or provider wrapper. The function normalizes inputs and returns a stable object for downstream use.

Parameters:

Name Type Description Default
user_input str

Value supplied to the helper.

required

Returns:

Type Description
str

Value produced by the build_prompt helper according to its function annotation and

str

return statements.

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

        Purpose:
            Builds the prompt value used by the Gipity interface or provider wrapper. The function
            normalizes inputs and returns a stable object for downstream use.

        Args:
            user_input (str): Value supplied to the helper.

        Returns:
            Value produced by the build_prompt helper according to its function annotation and
            return statements.
    """
	system_instructions = st.session_state.get( 'docqna_system_instructions', '' )
	use_semantic = bool( st.session_state.get( 'use_semantic', False ) )
	basic_docs = st.session_state.get( 'basic_docs', [ ] )
	messages = st.session_state.get( 'messages', [ ] )
	top_k_value = int( st.session_state.get( 'top_k', 0 ) )
	if top_k_value <= 0:
		top_k_value = 4
	prompt = f'<|system|>\n{system_instructions}\n</s>\n'
	if use_semantic:
		with sqlite3.connect( cfg.DB_PATH ) as conn:
			rows = conn.execute( 'SELECT chunk, vector FROM embeddings' ).fetchall( )
		if rows:
			q = embedder.encode( [ user_input ] )[ 0 ]
			scored = [ (c, cosine_sim( q, np.frombuffer( v ) )) for c, v in rows ]
			for c, _ in sorted( scored, key=lambda x: x[ 1 ], reverse=True )[ :top_k_value ]:
				prompt += f'<|system|>\n{c}\n</s>\n'
	for d in basic_docs[ :6 ]:
		prompt += f'<|system|>\n{d}\n</s>\n'
	if isinstance( messages, list ):
		for msg in messages:
			role = ''
			content = ''
			if isinstance( msg, tuple ) or isinstance( msg, list ):
				if len( msg ) == 2:
					role = str( msg[ 0 ] or '' ).strip( )
					content = str( msg[ 1 ] or '' )
			elif isinstance( msg, dict ):
				role = str( msg.get( 'role', '' ) or '' ).strip( )
				content = str( msg.get( 'content', '' ) or '' )
			if role:
				prompt += f'<|{role}|>\n{content}\n</s>\n'
	prompt += f'<|user|>\n{user_input}\n</s>\n<|assistant|>\n'
	return prompt

reset_audio_model_controls

reset_audio_model_controls() -> None

Reset audio model controls.

Purpose

Resets the audio model controls state used by the application. The function clears related Streamlit keys without performing provider calls.

Source code in app.py
def reset_audio_model_controls( ) -> None:
	"""Reset audio model controls.

        Purpose:
            Resets the audio model controls state used by the application. The function clears
            related Streamlit keys without performing provider calls.
    """
	st.session_state[ 'audio_task' ] = None
	st.session_state[ 'audio_model' ] = None
	st.session_state[ 'audio_language' ] = None
	st.session_state[ 'audio_background' ] = False
	st.session_state[ 'audio_reasoning' ] = None
	st.session_state[ 'audio_rate' ] = int( cfg.SAMPLE_RATES[ 0 ] ) if cfg.SAMPLE_RATES else 44100
	st.session_state[ 'audio_mime_type' ] = None

reset_audio_inference_controls

reset_audio_inference_controls() -> None

Reset audio inference controls.

Purpose

Resets the audio inference controls state used by the application. The function clears related Streamlit keys without performing provider calls.

Source code in app.py
def reset_audio_inference_controls( ) -> None:
	"""Reset audio inference controls.

        Purpose:
            Resets the audio inference controls state used by the application. The function clears
            related Streamlit keys without performing provider calls.
    """
	st.session_state[ 'audio_top_percent' ] = 0.0
	st.session_state[ 'audio_temperature' ] = 0.0
	st.session_state[ 'audio_presence_penalty' ] = 0.0
	st.session_state[ 'audio_frequency_penalty' ] = 0.0
	st.session_state[ 'audio_modalities' ] = [ ]
	st.session_state[ 'audio_response_format' ] = None

reset_audio_sound_controls

reset_audio_sound_controls() -> None

Reset audio sound controls.

Purpose

Resets the audio sound controls state used by the application. The function clears related Streamlit keys without performing provider calls.

Source code in app.py
def reset_audio_sound_controls( ) -> None:
	"""Reset audio sound controls.

        Purpose:
            Resets the audio sound controls state used by the application. The function clears
            related Streamlit keys without performing provider calls.
    """
	st.session_state[ 'audio_language' ] = None
	st.session_state[ 'audio_voice' ] = None
	st.session_state[ 'audio_loop' ] = False
	st.session_state[ 'audio_autoplay' ] = False
	st.session_state[ 'audio_start_time' ] = 0.0
	st.session_state[ 'audio_end_time' ] = 0.0

ensure_audio_mode_state

ensure_audio_mode_state() -> None

Ensure audio mode state.

Purpose

Ensures the required audio mode state session-state keys or runtime resources exist before the related interface controls are rendered.

Source code in app.py
def ensure_audio_mode_state( ) -> None:
	"""Ensure audio mode state.

        Purpose:
            Ensures the required audio mode state session-state keys or runtime resources exist
            before the related interface controls are rendered.
    """
	if 'audio_task' not in st.session_state:
		st.session_state[ 'audio_task' ] = ''
	if 'audio_model' not in st.session_state:
		st.session_state[ 'audio_model' ] = ''
	if 'audio_language' not in st.session_state:
		st.session_state[ 'audio_language' ] = ''
	if 'audio_response_format' not in st.session_state:
		st.session_state[ 'audio_response_format' ] = ''
	if 'audio_mime_type' not in st.session_state:
		st.session_state[ 'audio_mime_type' ] = ''
	if 'audio_include' not in st.session_state:
		st.session_state[ 'audio_include' ] = [ ]
	if 'audio_speed' not in st.session_state:
		st.session_state[ 'audio_speed' ] = 1.0
	if 'audio_voice' not in st.session_state:
		st.session_state[ 'audio_voice' ] = ''
	if 'audio_temperature' not in st.session_state:
		st.session_state[ 'audio_temperature' ] = 0.0
	if 'audio_system_instructions' not in st.session_state:
		st.session_state[ 'audio_system_instructions' ] = ''
	if 'audio_output' not in st.session_state:
		st.session_state[ 'audio_output' ] = ''
	if 'audio_output_bytes' not in st.session_state:
		st.session_state[ 'audio_output_bytes' ] = None
	if 'audio_last_result' not in st.session_state:
		st.session_state[ 'audio_last_result' ] = { }
	if 'audio_last_usage' not in st.session_state:
		st.session_state[ 'audio_last_usage' ] = { }
	if 'audio_messages' not in st.session_state:
		st.session_state.audio_messages = [ ]

get_audio_task_options

get_audio_task_options() -> List[str]

Get audio task options.

Purpose

Returns the audio task options value used by the Gipity interface. The helper centralizes option lookup and fallback behavior for callers.

Returns:

Type Description
List[str]

Value produced by the get_audio_task_options helper according to its function annotation

List[str]

and return statements.

Source code in app.py
def get_audio_task_options( ) -> List[ str ]:
	"""Get audio task options.

        Purpose:
            Returns the audio task options value used by the Gipity interface. The helper
            centralizes option lookup and fallback behavior for callers.

        Returns:
            Value produced by the get_audio_task_options helper according to its function annotation
            and return statements.
    """
	return [ '', 'Transcribe', 'Translate', 'Text-to-Speech' ]

get_audio_model_options

get_audio_model_options(
    task: str | None,
    transcriber: Transcription,
    translator: Translation,
    tts: TTS,
) -> List[str]

Get audio model options.

Purpose

Returns the audio model options value used by the Gipity interface. The helper centralizes option lookup and fallback behavior for callers.

Parameters:

Name Type Description Default
task str | None

Value supplied to the helper.

required
transcriber Transcription

Value supplied to the helper.

required
translator Translation

Value supplied to the helper.

required
tts TTS

Value supplied to the helper.

required

Returns:

Type Description
List[str]

Value produced by the get_audio_model_options helper according to its function

List[str]

annotation and return statements.

Source code in app.py
def get_audio_model_options( task: str | None, transcriber: Transcription,
	translator: Translation, tts: TTS ) -> List[ str ]:
	"""Get audio model options.

        Purpose:
            Returns the audio model options value used by the Gipity interface. The helper
            centralizes option lookup and fallback behavior for callers.

        Args:
            task (str | None): Value supplied to the helper.
            transcriber (Transcription): Value supplied to the helper.
            translator (Translation): Value supplied to the helper.
            tts (TTS): Value supplied to the helper.

        Returns:
            Value produced by the get_audio_model_options helper according to its function
            annotation and return statements.
    """
	if task == 'Transcribe':
		options = getattr( transcriber, 'model_options', [ ] )
	elif task == 'Translate':
		options = getattr( translator, 'model_options', [ ] )
	elif task == 'Text-to-Speech':
		options = getattr( tts, 'model_options', [ ] )
	else:
		options = [ ]
	if isinstance( options, list ) and len( options ) > 0:
		return [ '' ] + options
	return [ '' ]

get_audio_language_options

get_audio_language_options(
    transcriber: Transcription,
) -> List[str]

Get audio language options.

Purpose

Returns the audio language options value used by the Gipity interface. The helper centralizes option lookup and fallback behavior for callers.

Parameters:

Name Type Description Default
transcriber Transcription

Value supplied to the helper.

required

Returns:

Type Description
List[str]

Value produced by the get_audio_language_options helper according to its function

List[str]

annotation and return statements.

Source code in app.py
def get_audio_language_options( transcriber: Transcription ) -> List[ str ]:
	"""Get audio language options.

        Purpose:
            Returns the audio language options value used by the Gipity interface. The helper
            centralizes option lookup and fallback behavior for callers.

        Args:
            transcriber (Transcription): Value supplied to the helper.

        Returns:
            Value produced by the get_audio_language_options helper according to its function
            annotation and return statements.
    """
	options = getattr( transcriber, 'language_options', [ ] )
	if isinstance( options, list ) and len( options ) > 0:
		return [ '' ] + options
	return [ '' ]

get_audio_voice_options

get_audio_voice_options(
    tts: TTS, model: str = None
) -> List[str]

Get audio voice options.

Purpose

Returns the text-to-speech voices supported by the selected OpenAI speech model. The function prevents voices available only to GPT-4o Mini TTS from being submitted to the legacy TTS models.

Parameters:

Name Type Description Default
tts TTS

Text-to-speech wrapper exposing the complete voice option collection.

required
model str

Selected OpenAI text-to-speech model identifier.

None

Returns:

Type Description
List[str]

List[ str ]: Model-compatible voice options with an empty selector option.

Source code in app.py
def get_audio_voice_options( tts: TTS, model: str = None ) -> List[ str ]:
	"""Get audio voice options.

	Purpose:
		Returns the text-to-speech voices supported by the selected OpenAI speech model. The
		function prevents voices available only to GPT-4o Mini TTS from being submitted to the
		legacy TTS models.

	Args:
		tts (TTS): Text-to-speech wrapper exposing the complete voice option collection.
		model (str): Selected OpenAI text-to-speech model identifier.

	Returns:
		List[ str ]: Model-compatible voice options with an empty selector option.
	"""
	all_options = getattr( tts, 'voice_options', [ ] )

	if not isinstance( all_options, list ) or len( all_options ) == 0:
		return [ '' ]

	model_name = model.strip( ) if isinstance( model, str ) else ''

	if model_name in [ 'tts-1', 'tts-1-hd' ]:
		supported = [
				'alloy',
				'ash',
				'coral',
				'echo',
				'fable',
				'onyx',
				'nova',
				'sage',
				'shimmer',
		]

		options = [
				voice for voice in all_options
				if isinstance( voice, str ) and voice in supported
		]

		return [ '' ] + options

	return [ '' ] + [
			voice for voice in all_options
			if isinstance( voice, str ) and voice.strip( )
	]

get_audio_speed_options

get_audio_speed_options(tts: TTS) -> List[float]

Get audio speed options.

Purpose

Returns the audio speed options value used by the Gipity interface. The helper centralizes option lookup and fallback behavior for callers.

Parameters:

Name Type Description Default
tts TTS

Value supplied to the helper.

required

Returns:

Type Description
List[float]

Value produced by the get_audio_speed_options helper according to its function

List[float]

annotation and return statements.

Source code in app.py
def get_audio_speed_options( tts: TTS ) -> List[ float ]:
	"""Get audio speed options.

        Purpose:
            Returns the audio speed options value used by the Gipity interface. The helper
            centralizes option lookup and fallback behavior for callers.

        Args:
            tts (TTS): Value supplied to the helper.

        Returns:
            Value produced by the get_audio_speed_options helper according to its function
            annotation and return statements.
    """
	options = getattr( tts, 'speed_options', [ ] )
	if isinstance( options, list ) and len( options ) > 0:
		return options
	return [ 0.25, 0.5, 0.75, 1.0, 1.25, 1.5, 2.0, 3.0, 4.0 ]

get_audio_response_format_options

get_audio_response_format_options(
    task: str | None,
    model: str | None,
    transcriber: Transcription,
    translator: Translation,
    tts: TTS,
) -> List[str]

Get audio response format options.

Purpose

Returns the audio response format options value used by the Gipity interface. The helper centralizes option lookup and fallback behavior for callers.

Parameters:

Name Type Description Default
task str | None

Value supplied to the helper.

required
model str | None

Value supplied to the helper.

required
transcriber Transcription

Value supplied to the helper.

required
translator Translation

Value supplied to the helper.

required
tts TTS

Value supplied to the helper.

required

Returns:

Type Description
List[str]

Value produced by the get_audio_response_format_options helper according to its function

List[str]

annotation and return statements.

Source code in app.py
def get_audio_response_format_options( task: str | None, model: str | None,
		transcriber: Transcription, translator: Translation, tts: TTS ) -> List[ str ]:
	"""Get audio response format options.

        Purpose:
            Returns the audio response format options value used by the Gipity interface. The helper
            centralizes option lookup and fallback behavior for callers.

        Args:
            task (str | None): Value supplied to the helper.
            model (str | None): Value supplied to the helper.
            transcriber (Transcription): Value supplied to the helper.
            translator (Translation): Value supplied to the helper.
            tts (TTS): Value supplied to the helper.

        Returns:
            Value produced by the get_audio_response_format_options helper according to its function
            annotation and return statements.
    """
	if task == 'Transcribe':
		format_map = getattr( transcriber, 'response_format_options', { } )
		if isinstance( format_map, dict ):
			options = format_map.get( model, [ 'json' ] )
			return [ '' ] + options
		return [ '', 'json' ]
	if task == 'Translate':
		options = getattr( translator, 'response_format_options', [ ] )
		if isinstance( options, list ) and len( options ) > 0:
			return [ '' ] + options
		return [ '', 'json', 'text', 'srt', 'verbose_json', 'vtt' ]
	if task == 'Text-to-Speech':
		options = getattr( tts, 'mime_options', [ ] )
		if isinstance( options, list ) and len( options ) > 0:
			return [ '' ] + options
		return [ '', 'mp3', 'opus', 'aac', 'flac', 'wav', 'pcm' ]
	return [ '' ]

get_audio_include_options

get_audio_include_options(
    task: str | None,
    model: str | None,
    transcriber: Transcription,
) -> List[str]

Get audio include options.

Purpose

Returns the audio include options value used by the Gipity interface. The helper centralizes option lookup and fallback behavior for callers.

Parameters:

Name Type Description Default
task str | None

Value supplied to the helper.

required
model str | None

Value supplied to the helper.

required
transcriber Transcription

Value supplied to the helper.

required

Returns:

Type Description
List[str]

Value produced by the get_audio_include_options helper according to its function

List[str]

annotation and return statements.

Source code in app.py
def get_audio_include_options( task: str | None, model: str | None,
	transcriber: Transcription ) -> List[ str ]:
	"""Get audio include options.

        Purpose:
            Returns the audio include options value used by the Gipity interface. The helper
            centralizes option lookup and fallback behavior for callers.

        Args:
            task (str | None): Value supplied to the helper.
            model (str | None): Value supplied to the helper.
            transcriber (Transcription): Value supplied to the helper.

        Returns:
            Value produced by the get_audio_include_options helper according to its function
            annotation and return statements.
    """
	if task != 'Transcribe':
		return [ ]
	if model not in [ 'gpt-4o-transcribe', 'gpt-4o-mini-transcribe',
	                  'gpt-4o-mini-transcribe-2025-12-15' ]:
		return [ ]
	options = getattr( transcriber, 'include_options', [ ] )
	if isinstance( options, list ) and len( options ) > 0:
		return options
	return [ 'logprobs' ]

get_audio_response_format_value

get_audio_response_format_value(
    task: str | None,
    selected_format: str | None,
    selected_mime_type: str | None = None,
) -> str | None

Get audio response format value.

Purpose

Returns the audio response format value value used by the Gipity interface. The helper centralizes option lookup and fallback behavior for callers.

Parameters:

Name Type Description Default
task str | None

Value supplied to the helper.

required
selected_format str | None

Value supplied to the helper.

required
selected_mime_type str | None

Value supplied to the helper.

None

Returns:

Type Description
str | None

Value produced by the get_audio_response_format_value helper according to its function

str | None

annotation and return statements.

Source code in app.py
def get_audio_response_format_value( task: str | None, selected_format: str | None,
		selected_mime_type: str | None = None ) -> str | None:
	"""Get audio response format value.

        Purpose:
            Returns the audio response format value value used by the Gipity interface. The helper
            centralizes option lookup and fallback behavior for callers.

        Args:
            task (str | None): Value supplied to the helper.
            selected_format (str | None): Value supplied to the helper.
            selected_mime_type (str | None): Value supplied to the helper.

        Returns:
            Value produced by the get_audio_response_format_value helper according to its function
            annotation and return statements.
    """
	if task == 'Text-to-Speech':
		if isinstance( selected_format, str ) and selected_format.strip( ):
			return selected_format.strip( )
		if isinstance( selected_mime_type, str ) and selected_mime_type.strip( ):
			return selected_mime_type.strip( )
		return 'mp3'
	if isinstance( selected_format, str ) and selected_format.strip( ):
		return selected_format.strip( )
	return None

get_audio_prompt_value

get_audio_prompt_value(
    task: str | None, prompt: str | None
) -> str | None

Get audio prompt value.

Purpose

Returns the audio prompt value value used by the Gipity interface. The helper centralizes option lookup and fallback behavior for callers.

Parameters:

Name Type Description Default
task str | None

Value supplied to the helper.

required
prompt str | None

Value supplied to the helper.

required

Returns:

Type Description
str | None

Value produced by the get_audio_prompt_value helper according to its function annotation

str | None

and return statements.

Source code in app.py
def get_audio_prompt_value( task: str | None, prompt: str | None ) -> str | None:
	"""Get audio prompt value.

        Purpose:
            Returns the audio prompt value value used by the Gipity interface. The helper
            centralizes option lookup and fallback behavior for callers.

        Args:
            task (str | None): Value supplied to the helper.
            prompt (str | None): Value supplied to the helper.

        Returns:
            Value produced by the get_audio_prompt_value helper according to its function annotation
            and return statements.
    """
	if not isinstance( prompt, str ) or not prompt.strip( ):
		return None
	if task in [ 'Transcribe', 'Translate', 'Text-to-Speech' ]:
		return prompt.strip( )
	return None

save_audio_upload

save_audio_upload(upload: Any) -> str | None

Save audio upload.

Purpose

Saves the audio upload value for later workflow use while preserving the caller-facing return contract.

Parameters:

Name Type Description Default
upload Any

Value supplied to the helper.

required

Returns:

Type Description
str | None

Value produced by the save_audio_upload helper according to its function annotation and

str | None

return statements.

Source code in app.py
def save_audio_upload( upload: Any ) -> str | None:
	"""Save audio upload.

        Purpose:
            Saves the audio upload value for later workflow use while preserving the caller-facing
            return contract.

        Args:
            upload (Any): Value supplied to the helper.

        Returns:
            Value produced by the save_audio_upload helper according to its function annotation and
            return statements.
    """
	if upload is None:
		return None
	try:
		name = getattr( upload, 'name', '' )
		_, ext = os.path.splitext( name )
		if not ext:
			ext = '.wav'
		with tempfile.NamedTemporaryFile( delete=False, suffix=ext ) as tmp:
			if hasattr( upload, 'getbuffer' ):
				tmp.write( upload.getbuffer( ) )
			elif hasattr( upload, 'read' ):
				tmp.write( upload.read( ) )
			else:
				return None
			return tmp.name
	except Exception as e:
		exception = Error( e )
		exception.module = 'app'
		exception.cause = 'save_audio_upload'
		exception.method = 'save_audio_upload( ... )'
		Logger( ).write( exception )
		return None

render_audio_segments

render_audio_segments(
    result: Dict[str, Any] | None,
) -> None

Render audio segments.

Purpose

Renders the audio segments user-interface section or display element in Streamlit while preserving the application state expected by the surrounding workflow.

Parameters:

Name Type Description Default
result Dict[str, Any] | None

Value supplied to the helper.

required
Source code in app.py
def render_audio_segments( result: Dict[ str, Any ] | None ) -> None:
	"""Render audio segments.

        Purpose:
            Renders the audio segments user-interface section or display element in Streamlit while
            preserving the application state expected by the surrounding workflow.

        Args:
            result (Dict[str, Any] | None): Value supplied to the helper.
    """
	if not isinstance( result, dict ):
		return
	segments = result.get( 'segments' )
	if not isinstance( segments, list ) or len( segments ) == 0:
		return
	rows: List[ Dict[ str, Any ] ] = [ ]
	for index, segment in enumerate( segments, start=1 ):
		if not isinstance( segment, dict ):
			continue
		rows.append( { 'Index': index,
		               'Speaker': segment.get( 'speaker' ) or segment.get( 'speaker_id' ) or '',
		               'Start': segment.get( 'start' ) or segment.get( 'start_time' ) or '',
		               'End': segment.get( 'end' ) or segment.get( 'end_time' ) or '',
		               'Text': segment.get( 'text' ) or '' } )
	if len( rows ) == 0:
		return
	df_segments = pd.DataFrame( rows )
	st.caption( 'Segments' )
	st.data_editor( df_segments, use_container_width=True, hide_index=True )

render_audio_text_result

render_audio_text_result(
    title: str,
    result_text: str | None,
    result: Dict[str, Any] | None = None,
) -> None

Render audio text result.

Purpose

Renders the audio text result user-interface section or display element in Streamlit while preserving the application state expected by the surrounding workflow.

Parameters:

Name Type Description Default
title str

Value supplied to the helper.

required
result_text str | None

Value supplied to the helper.

required
result Dict[str, Any] | None

Value supplied to the helper.

None
Source code in app.py
def render_audio_text_result( title: str, result_text: str | None,
		result: Dict[ str, Any ] | None = None ) -> None:
	"""Render audio text result.

        Purpose:
            Renders the audio text result user-interface section or display element in Streamlit
            while preserving the application state expected by the surrounding workflow.

        Args:
            title (str): Value supplied to the helper.
            result_text (str | None): Value supplied to the helper.
            result (Dict[str, Any] | None): Value supplied to the helper.
    """
	text_value = result_text if isinstance( result_text, str ) else ''
	st.text_area( title, value=text_value, height=250, width='stretch' )
	if isinstance( result, dict ):
		language = result.get( 'language' )
		duration = result.get( 'duration' )
		if language or duration:
			m1, m2 = st.columns( [ 0.5, 0.5 ] )
			with m1:
				st.metric( 'Language', language or '—' )
			with m2:
				st.metric( 'Duration', duration or '—' )
		render_audio_segments( result )

extract_audio_usage

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

Extract audio usage.

Purpose

Extracts the audio usage value from the supplied object or payload while handling missing or unsupported content safely.

Parameters:

Name Type Description Default
response Any

Value supplied to the helper.

required

Returns:

Type Description
Dict[str, Any]

Value produced by the extract_audio_usage helper according to its function annotation

Dict[str, Any]

and return statements.

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

        Purpose:
            Extracts the audio usage value from the supplied object or payload while handling
            missing or unsupported content safely.

        Args:
            response (Any): Value supplied to the helper.

        Returns:
            Value produced by the extract_audio_usage helper according to its function annotation
            and return statements.
    """
	usage: Dict[ str, Any ] = { }
	if response is None:
		return usage
	try:
		raw = getattr( response, 'usage', None )
	except Exception as e:
		exception = Error( e )
		exception.module = 'app'
		exception.cause = 'extract_audio_usage'
		exception.method = 'extract_audio_usage( ... )'
		Logger( ).write( exception )
		raw = None
	if raw is None:
		return usage
	if isinstance( raw, dict ):
		return raw
	if hasattr( raw, 'model_dump' ):
		try:
			return raw.model_dump( )
		except Exception as e:
			exception = Error( e )
			exception.module = 'app'
			exception.cause = 'extract_audio_usage'
			exception.method = 'extract_audio_usage( ... )'
			Logger( ).write( exception )
			return { 'raw': str( raw ) }
	return { 'raw': str( raw ) }

run_audio_file_task

run_audio_file_task(
    task: str | None,
    file_path: str | None,
    transcriber: Transcription,
    translator: Translation,
) -> str | None

Run audio file task.

Purpose

Runs the audio file task workflow from the Streamlit interface by validating current inputs, calling the appropriate wrapper or helper, and storing relevant output state.

Parameters:

Name Type Description Default
task str | None

Value supplied to the helper.

required
file_path str | None

Value supplied to the helper.

required
transcriber Transcription

Value supplied to the helper.

required
translator Translation

Value supplied to the helper.

required

Returns:

Type Description
str | None

Value produced by the run_audio_file_task helper according to its function annotation

str | None

and return statements.

Source code in app.py
def run_audio_file_task( task: str | None, file_path: str | None, transcriber: Transcription,
		translator: Translation ) -> str | None:
	"""Run audio file task.

        Purpose:
            Runs the audio file task workflow from the Streamlit interface by validating current
            inputs, calling the appropriate wrapper or helper, and storing relevant output state.

        Args:
            task (str | None): Value supplied to the helper.
            file_path (str | None): Value supplied to the helper.
            transcriber (Transcription): Value supplied to the helper.
            translator (Translation): Value supplied to the helper.

        Returns:
            Value produced by the run_audio_file_task helper according to its function annotation
            and return statements.
    """
	if not isinstance( task, str ) or not task.strip( ):
		st.warning( 'Select an audio task before processing audio.' )
		return None
	if not isinstance( file_path, str ) or not file_path.strip( ):
		st.warning( 'Upload or record audio before processing.' )
		return None
	prompt = get_audio_prompt_value( task, st.session_state.get( 'audio_system_instructions', '' ) )
	response_format = get_audio_response_format_value( task=task,
		selected_format=st.session_state.get( 'audio_response_format' ),
		selected_mime_type=st.session_state.get( 'audio_mime_type' ) )
	model = st.session_state.get( 'audio_model' )
	language = st.session_state.get( 'audio_language' )
	temperature = st.session_state.get( 'audio_temperature' )
	include = st.session_state.get( 'audio_include', [ ] )
	if task == 'Transcribe':
		result_text = transcriber.transcribe( path=file_path, model=model or 'gpt-4o-transcribe',
			language=language or None, prompt=prompt, format=response_format,
			temperature=temperature, include=include )
		result = getattr( transcriber, 'normalized_result', { } )
		st.session_state[ 'audio_output' ] = result_text or ''
		st.session_state[ 'audio_last_result' ] = result if isinstance( result, dict ) else { }
		st.session_state[ 'audio_last_usage' ] = extract_audio_usage(
			getattr( transcriber, 'response', None ) )
		return result_text
	if task == 'Translate':
		result_text = translator.translate( filepath=file_path, model=model or 'whisper-1',
			prompt=prompt, format=response_format, temperature=temperature,
			language=language or None )
		result = getattr( translator, 'normalized_result', { } )
		st.session_state[ 'audio_output' ] = result_text or ''
		st.session_state[ 'audio_last_result' ] = result if isinstance( result, dict ) else { }
		st.session_state[ 'audio_last_usage' ] = extract_audio_usage(
			getattr( translator, 'response', None ) )
		return result_text
	if task == 'Text-to-Speech':
		st.info( 'Use the Text-to-Speech input area to generate speech from text.' )
		return None
	return None

run_audio_tts_task

run_audio_tts_task(
    text: str | None, tts: TTS
) -> bytes | None

Run audio tts task.

Purpose

Runs the audio tts task workflow from the Streamlit interface by validating current inputs, calling the appropriate wrapper or helper, and storing relevant output state.

Parameters:

Name Type Description Default
text str | None

Value supplied to the helper.

required
tts TTS

Value supplied to the helper.

required

Returns:

Type Description
bytes | None

Value produced by the run_audio_tts_task helper according to its function annotation and

bytes | None

return statements.

Source code in app.py
def run_audio_tts_task( text: str | None, tts: TTS ) -> bytes | None:
	"""Run audio tts task.

        Purpose:
            Runs the audio tts task workflow from the Streamlit interface by validating current
            inputs, calling the appropriate wrapper or helper, and storing relevant output state.

        Args:
            text (str | None): Value supplied to the helper.
            tts (TTS): Value supplied to the helper.

        Returns:
            Value produced by the run_audio_tts_task helper according to its function annotation and
            return statements.
    """
	if not isinstance( text, str ) or not text.strip( ):
		st.warning( 'Enter text before generating speech.' )
		return None
	model = st.session_state.get( 'audio_model' ) or 'gpt-4o-mini-tts'
	voice = st.session_state.get( 'audio_voice' ) or 'alloy'
	speed = st.session_state.get( 'audio_speed', 1.0 )
	response_format = get_audio_response_format_value( task='Text-to-Speech',
		selected_format=st.session_state.get( 'audio_response_format' ),
		selected_mime_type=st.session_state.get( 'audio_mime_type' ) )
	instructions = get_audio_prompt_value( task='Text-to-Speech',
		prompt=st.session_state.get( 'audio_system_instructions', '' ) )
	audio_bytes = tts.create_speech( text=text.strip( ), model=model,
		format=response_format or 'mp3', speed=speed, voice=voice, instruct=instructions )
	st.session_state[ 'audio_output_bytes' ] = audio_bytes
	st.session_state[ 'audio_output' ] = text.strip( )
	st.session_state[ 'audio_last_result' ] = { 'text': text.strip( ),
	                                            'format': response_format or 'mp3', 'voice': voice,
	                                            'speed': speed }
	st.session_state[ 'audio_last_usage' ] = extract_audio_usage( getattr( tts, 'response', None ) )
	return audio_bytes

clear_audio_outputs

clear_audio_outputs() -> None

Clear audio outputs.

Purpose

Clears the audio outputs state used by the current workflow so the user interface can start from a clean output state.

Source code in app.py
def clear_audio_outputs( ) -> None:
	"""Clear audio outputs.

        Purpose:
            Clears the audio outputs state used by the current workflow so the user interface can
            start from a clean output state.
    """
	st.session_state[ 'audio_output' ] = ''
	st.session_state[ 'audio_output_bytes' ] = None
	st.session_state[ 'audio_last_result' ] = { }
	st.session_state[ 'audio_last_usage' ] = { }

clear_audio_messages

clear_audio_messages() -> None

Clear audio messages.

Purpose

Clears the audio messages state used by the current workflow so the user interface can start from a clean output state.

Source code in app.py
def clear_audio_messages( ) -> None:
	"""Clear audio messages.

        Purpose:
            Clears the audio messages state used by the current workflow so the user interface can
            start from a clean output state.
    """
	st.session_state.audio_messages = [ ]
	clear_audio_outputs( )

clear_audio_instructions

clear_audio_instructions() -> None

Clear audio instructions.

Purpose

Clears the audio instructions state used by the current workflow so the user interface can start from a clean output state.

Source code in app.py
def clear_audio_instructions( ) -> None:
	"""Clear audio instructions.

        Purpose:
            Clears the audio instructions state used by the current workflow so the user interface
            can start from a clean output state.
    """
	st.session_state[ 'audio_system_instructions' ] = ''
	st.session_state[ 'instructions' ] = ''

load_audio_instruction_template

load_audio_instruction_template() -> None

Load audio instruction template.

Purpose

Loads the audio instruction template resource or state required by the Gipity workflow and returns the prepared value for caller use.

Source code in app.py
def load_audio_instruction_template( ) -> None:
	"""Load audio instruction template.

        Purpose:
            Loads the audio instruction template resource or state required by the Gipity workflow
            and returns the prepared value for caller use.
    """
	name = st.session_state.get( 'instructions' )
	if name and name != 'No Templates Found':
		text = fetch_prompt_text( cfg.DB_PATH, name )
		if text is not None:
			st.session_state[ 'audio_system_instructions' ] = text

convert_audio_system_instructions

convert_audio_system_instructions() -> None

Convert audio system instructions.

Purpose

Provides the convert audio system instructions helper used by the Gipity Streamlit application. The function supports UI state management, provider coordination, data normalization, or display behavior required by the surrounding workflow.

Source code in app.py
def convert_audio_system_instructions( ) -> None:
	"""Convert audio system instructions.

        Purpose:
            Provides the convert audio system instructions helper used by the Gipity Streamlit
            application. The function supports UI state management, provider coordination, data
            normalization, or display behavior required by the surrounding workflow.
    """
	text = st.session_state.get( 'audio_system_instructions', '' )
	if not isinstance( text, str ) or not text.strip( ):
		return
	source = text.strip( )
	if cfg.XML_BLOCK_PATTERN.search( source ):
		converted = convert_xml( source )
	else:
		converted = convert_markdown( source )
	st.session_state[ 'audio_system_instructions' ] = converted

reset_audio_task_controls

reset_audio_task_controls() -> None

Reset audio task controls.

Purpose

Resets the audio task controls state used by the application. The function clears related Streamlit keys without performing provider calls.

Source code in app.py
def reset_audio_task_controls( ) -> None:
	"""Reset audio task controls.

        Purpose:
            Resets the audio task controls state used by the application. The function clears
            related Streamlit keys without performing provider calls.
    """
	for key in [ 'audio_task', 'audio_model', 'audio_language', 'audio_response_format',
	             'audio_include' ]:
		if key in st.session_state:
			del st.session_state[ key ]

reset_audio_tts_controls

reset_audio_tts_controls() -> None

Reset audio tts controls.

Purpose

Resets the audio tts controls state used by the application. The function clears related Streamlit keys without performing provider calls.

Source code in app.py
def reset_audio_tts_controls( ) -> None:
	"""Reset audio tts controls.

        Purpose:
            Resets the audio tts controls state used by the application. The function clears related
            Streamlit keys without performing provider calls.
    """
	for key in [ 'audio_voice', 'audio_speed', 'audio_mime_type' ]:
		if key in st.session_state:
			del st.session_state[ key ]

reset_text_llm_controls

reset_text_llm_controls() -> None

Reset text llm controls.

Purpose

Resets the text llm controls state used by the application. The function clears related Streamlit keys without performing provider calls.

Source code in app.py
	def reset_text_llm_controls( ) -> None:
		"""Reset text llm controls.

            Purpose:
                Resets the text llm controls state used by the application. The function clears related
                Streamlit keys without performing provider calls.
        """
		for key in [ 'text_model', 'text_temperature', 'text_presence_penalty', 'text_reasoning',
		             'text_top_percent', 'text_frequency_penalty' ]:
			if key in st.session_state:
				del st.session_state[ key ]

reset_text_tool_controls

reset_text_tool_controls() -> None

Reset text tool controls.

Purpose

Resets the text tool controls state used by the application. The function clears related Streamlit keys without performing provider calls.

Source code in app.py
	def reset_text_tool_controls( ) -> None:
		"""Reset text tool controls.

            Purpose:
                Resets the text tool controls state used by the application. The function clears related
                Streamlit keys without performing provider calls.
        """
		for key in [ 'text_max_calls', 'text_tool_choice', 'text_include', 'text_tools',
		             'text_domains_input', 'text_domains', 'text_parallel_calls',
		             'text_vector_store_ids' ]:
			if key in st.session_state:
				del st.session_state[ key ]

reset_text_response_controls

reset_text_response_controls() -> None

Reset text response controls.

Purpose

Resets the Text mode response-control state without modifying model, tool, prompt-template, conversation-message, or database state.

Returns:

Name Type Description
None None

The function removes the response-control keys from Streamlit session state.

Source code in app.py
def reset_text_response_controls( ) -> None:
	"""Reset text response controls.

	Purpose:
	    Resets the Text mode response-control state without modifying model, tool,
	    prompt-template, conversation-message, or database state.

	Returns:
	    None: The function removes the response-control keys from Streamlit session state.
	"""
	for key in [ 'text_stream', 'text_store', 'text_max_tokens', 'text_background',
		'text_response_format', 'text_input', 'text_previous_response_id',
		'text_conversation_id', ]:
		if key in st.session_state:
			del st.session_state[ key ]

clear_files_current_selection

clear_files_current_selection() -> None

Clear the current Files API selection.

Purpose

Clears the selected file and its file-specific outputs without deleting the remote file or clearing the current Files API listing.

Returns:

Name Type Description
None None

This function updates Files mode selection and output state.

Source code in app.py
def clear_files_current_selection( ) -> None:
	"""Clear the current Files API selection.

	Purpose:
		Clears the selected file and its file-specific outputs without deleting the remote file
		or clearing the current Files API listing.

	Returns:
		None: This function updates Files mode selection and output state.
	"""
	st.session_state[ 'files_id' ] = ''
	st.session_state[ 'files_manual_id' ] = ''
	st.session_state[ 'files_selected_label' ] = ''
	st.session_state[ 'files_selected_row_id' ] = ''
	st.session_state[ 'files_metadata' ] = { }
	st.session_state[ 'files_content' ] = ''
	st.session_state[ 'files_content_bytes' ] = None
	st.session_state[ 'files_delete_result' ] = { }

	if 'files_table_selector' in st.session_state:
		del st.session_state[ 'files_table_selector' ]

reset_files_workspace

reset_files_workspace() -> None

Reset the complete Files API workspace.

Purpose

Clears Files mode controls, file listings, current selection, outputs, and messages while leaving remote OpenAI files unchanged.

Returns:

Name Type Description
None None

This function resets Files mode session state.

Source code in app.py
def reset_files_workspace( ) -> None:
	"""Reset the complete Files API workspace.

	Purpose:
		Clears Files mode controls, file listings, current selection, outputs, and messages
		while
		leaving remote OpenAI files unchanged.

	Returns:
		None: This function resets Files mode session state.
	"""
	reset_files_all( )
	st.session_state[ 'files_manual_id' ] = ''
	st.session_state[ 'files_selected_label' ] = ''
	st.session_state[ 'files_selected_row_id' ] = ''

	if 'files_table_selector' in st.session_state:
		del st.session_state[ 'files_table_selector' ]

get_conn

get_conn() -> str

Get conn.

Purpose

Returns the conn value used by the Gipity interface. The helper centralizes option lookup and fallback behavior for callers.

Returns:

Type Description
str

Value produced by the get_conn helper according to its function annotation

str

and return

str

statements.

Source code in app.py
		def get_conn( ) -> str:
			"""Get conn.

                Purpose:
                    Returns the conn value used by the Gipity interface. The helper centralizes
                    option
                    lookup and fallback behavior for callers.

                Returns:
                    Value produced by the get_conn helper according to its function annotation
                    and return
                    statements.
            """
			return sqlite3.connect( cfg.DB_PATH )

reset_selection

reset_selection()

Reset selection.

Purpose

Resets the selection state used by the application. The function clears related Streamlit keys without performing provider calls.

Source code in app.py
		def reset_selection( ):
			"""Reset selection.

                Purpose:
                    Resets the selection state used by the application. The function clears related
                    Streamlit keys without performing provider calls.
            """
			st.session_state.pe_selected_id = None
			st.session_state.pe_caption = ''
			st.session_state.pe_name = ''
			st.session_state.pe_text = ''
			st.session_state.pe_version = ''
			st.session_state.pe_id = 0

load_prompt

load_prompt(pid: int) -> None

Load prompt.

Purpose

Loads the prompt resource or state required by the Gipity workflow and returns the prepared value for caller use.

Parameters:

Name Type Description Default
pid int

Value supplied to the helper.

required
Source code in app.py
		def load_prompt( pid: int ) -> None:
			"""Load prompt.

                Purpose:
                    Loads the prompt resource or state required by the Gipity workflow and
                    returns the
                    prepared value for caller use.

                Args:
                    pid (int): Value supplied to the helper.
            """
			with get_conn( ) as conn:
				_select = f'SELECT Caption, Name, Text, Version, ID FROM {TABLE} WHERE PromptsId=?'
				cur = conn.execute( _select, (pid,) )
				row = cur.fetchone( )
				if not row:
					return
				st.session_state.pe_caption = row[ 0 ]
				st.session_state.pe_name = row[ 1 ]
				st.session_state.pe_text = row[ 2 ]
				st.session_state.pe_version = row[ 3 ]
				st.session_state.pe_id = row[ 4 ]