Configure bia-bob’s behaviour through system messages#

In this notebook we demonstrate how you can configure what kind of Python code bia-bob will generate. Note that the following configuration will be stored across sessions. When installing a new version of bia-bob, these settings are reset. You can also manually reset bia-bob’s configuration by deleting the .cache\bia-bob directory in your home directory.

from bia_bob import bob, DEFAULT_SYSTEM_PROMPT
bob.initialize(endpoint="ollama",
               api_key="none", 
               model="gemma3:4b")

bob.__version__
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
Cell In[1], line 1
----> 1 from bia_bob import bob, DEFAULT_SYSTEM_PROMPT
      2 bob.initialize(endpoint="ollama",
      3                api_key="none", 
      4                model="gemma3:4b")
      6 bob.__version__

ImportError: cannot import name 'DEFAULT_SYSTEM_PROMPT' from 'bia_bob' (C:\Users\rober\miniforge3\envs\secai-llm2\Lib\site-packages\bia_bob\__init__.py)

Default behaviour#

Per default, bia-bob will write Python code using specific bio-image analysis Python libraries. That’s because its default system messages configures this behaviour:

print(DEFAULT_SYSTEM_PROMPT[:640])
You are a extremely talented bioimage analyst and you use Python to solve your tasks unless stated otherwise.
If there are several ways to solve the task, chose the option with the least amount of code.    

## Python specific instructions

When writing python code, you can only use those libraries: {libraries}.
If you create images, show the results and save them in variables for later reuse.
{reusable_variables}
NEVER overwrite the values of the variables and functions that are available.

## Python specific code snippets

If the user asks for those simple tasks, use these code snippets.

{additional_snippets}
{builtin_snippets}

Note that libraries, reusable variables and snippets will be injected when bia-bob is invoked. You can use these placeholders in your custom system prompts, too.

%bob print hello world
This notebook may contain text, code and images generated by artificial intelligence. Used model: claude-3-5-sonnet-20241022, vision model: claude-3-5-sonnet-20241022, endpoint: None, bia-bob version: 0.26.0.. Do not enter sensitive or private information and verify generated contents according to good scientific practice. Read more: https://github.com/haesleinhuepf/bia-bob#disclaimer
print("hello world")

Custom system messages#

You can configure your own system message. In the following example we enforce bob to always just answer a given question and never write code.

bob.initialize(system_prompt="""
    You are an excellent Python programmer who always 
    uses Finnish variable names in their code.
    """)
This notebook may contain text, code and images generated by artificial intelligence. Used model: claude-3-5-sonnet-20241022, vision model: claude-3-5-sonnet-20241022, endpoint: None, bia-bob version: 0.26.0.. Do not enter sensitive or private information and verify generated contents according to good scientific practice. Read more: https://github.com/haesleinhuepf/bia-bob#disclaimer
%bob Write a for-loop that prints the numbers from 0 to 10.
for luku in range(11):
    print(luku)

Default system message#

You can reset the config to the default system message like this:

bob.initialize(system_prompt=DEFAULT_SYSTEM_PROMPT)
This notebook may contain text, code and images generated by artificial intelligence. Used model: claude-3-5-sonnet-20241022, vision model: claude-3-5-sonnet-20241022, endpoint: None, bia-bob version: 0.26.0.. Do not enter sensitive or private information and verify generated contents according to good scientific practice. Read more: https://github.com/haesleinhuepf/bia-bob#disclaimer
%bob print hello world
print("hello world")

Short Python system message#

If you work with small, local, open-weight language models, e.g. via ollama it might make sense to provide very short system messages:

bob.initialize(system_prompt="""
    Write Python code for the following task and ensure that the functionality is embedded in a function. 
    Also give an example how to call the function.
    """)
This notebook may contain text, code and images generated by artificial intelligence. Used model: claude-3-5-sonnet-20241022, vision model: claude-3-5-sonnet-20241022, endpoint: None, bia-bob version: 0.26.0.. Do not enter sensitive or private information and verify generated contents according to good scientific practice. Read more: https://github.com/haesleinhuepf/bia-bob#disclaimer
%bob print hello world
def print_hello_world():
    print("Hello World")

# Calling the function
print_hello_world()

Domain specific system messages#

You can instruct bia-bob to use common Python libraries from specific domains.

from bia_bob import bob
bob.initialize(system_prompt="""
    You are an excellent astronomer and Python programmer.
    You typically use Python libraris from this domain.
""")
This notebook may contain text, code and images generated by artificial intelligence. Used model: claude-3-5-sonnet-20241022, vision model: claude-3-5-sonnet-20241022, endpoint: None, bia-bob version: 0.26.0.. Do not enter sensitive or private information and verify generated contents according to good scientific practice. Read more: https://github.com/haesleinhuepf/bia-bob#disclaimer
%bob Write a function that can detect stars in an image.
from astropy.io import fits
from photutils import DAOStarFinder
from astropy.stats import sigma_clipped_stats
import numpy as np

def detect_stars(image_data, fwhm=3.0, threshold=5.0):
    """
    Detect stars in an astronomical image using DAOStarFinder.
    
    Parameters:
    -----------
    image_data : numpy.ndarray
        The 2D image array where stars should be detected
    fwhm : float
        The Full-Width Half-Maximum (FWHM) of the stellar profiles
    threshold : float
        The detection threshold in terms of sigma above background
    
    Returns:
    --------
    sources : Table
        Table of detected sources with their properties
    """
    try:
        # Calculate background statistics using sigma-clipping
        mean, median, std = sigma_clipped_stats(image_data, sigma=3.0)
        
        # Create a DAOStarFinder object
        daofind = DAOStarFinder(fwhm=fwhm, 
                               threshold=threshold*std,
                               sharplo=0.2,
                               sharphi=1.0,
                               roundlo=-0.7,
                               roundhi=0.7)
        
        # Find stars
        sources = daofind(image_data - median)
        
        if sources is None:
            return None
            
        return sources
        
    except Exception as e:
        print(f"Error during star detection: {str(e)}")
        return None

# Example usage:
def process_fits_image(fits_path):
    """
    Example function showing how to use detect_stars with a FITS file.
    
    Parameters:
    -----------
    fits_path : str 
        Path to the FITS file
    """
    try:
        # Open the FITS file
        with fits.open(fits_path) as hdul:
            # Assuming the image is in the primary HDU
            image_data = hdul[0].data
            
            # Detect stars
            sources = detect_stars(image_data)
            
            if sources is not None:
                print(f"Found {len(sources)} stars")
                print("Star positions (x, y):")
                for source in sources:
                    print(f"({source['xcentroid']:.2f}, {source['ycentroid']:.2f})")
            else:
                print("No stars detected")
                
    except Exception as e:
        print(f"Error processing FITS file: {str(e)}")

# For a FITS file
process_fits_image('path/to/your/image.fits')

# For a numpy array
image_data = fits.getdata('path/to/your/image.fits')

# Detect stars
sources = detect_stars(image_data)
if sources is not None:
    print(f"Found {len(sources)} stars")

Terrible system messages#

You can also instruct bia-bob to do stupid things. Be careful with this functionality.

bob.initialize(system_prompt="""
    You always write super complicated, hard-to-read Python code 
    surrounded with markdown fences. 
    with a lot of unnecessary loops and weird variable names. 
    Make sure it consists of at least 5 lines of code.
""")
This notebook may contain text, code and images generated by artificial intelligence. Used model: claude-3-5-sonnet-20241022, vision model: claude-3-5-sonnet-20241022, endpoint: None, bia-bob version: 0.26.0.. Do not enter sensitive or private information and verify generated contents according to good scientific practice. Read more: https://github.com/haesleinhuepf/bia-bob#disclaimer
%bob print hello world
def generate_msg_components():
    msg_chars = ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
    temp_storage = []
    for idx in range(len(msg_chars)):
        _current_char = msg_chars[idx]
        temp_storage.append(_current_char)
    return ''.join([char for char in temp_storage])

final_output_str = ''
intermediate_result = generate_msg_components()
for iteration_count in range(1):
    final_output_str += intermediate_result
    
print(final_output_str)
# Reset default behaviour, as it would be stored permanently otherwise.
bob.initialize(system_prompt=DEFAULT_SYSTEM_PROMPT)
This notebook may contain text, code and images generated by artificial intelligence. Used model: claude-3-5-sonnet-20241022, vision model: claude-3-5-sonnet-20241022, endpoint: None, bia-bob version: 0.26.0.. Do not enter sensitive or private information and verify generated contents according to good scientific practice. Read more: https://github.com/haesleinhuepf/bia-bob#disclaimer