Tuesday, 22 April 2025

Getting Started with Ollama Chat API: Building an AI-Powered Chat Application

In this post, I am going to explain Ollama's Chat API and how it can be used to interact with AI-powered models like "llama3.2".

 

What is Ollama Chat API?

Ollama Chat API is a platform that provides seamless access to conversational AI models. It simplifies integrating and using language models in your applications, making it perfect for developers looking to build chatbots, Q&A systems, and more.

 

helloChat.py 

import ollama

response = ollama.chat(
    model = "llama3.2",
    messages = [
        {"role" : "user", "content" : "Tell me about Solar System"}
    ]
)

print(response["message"]["content"])

Output

The Solar System is a vast and fascinating place, consisting of eight planets, dwarf planets, asteroids, comets, and other celestial objects that orbit around the Sun. Here's an overview:

**Structure of the Solar System:**

1. **Sun:** The center of our solar system, the Sun is a massive ball of hot, glowing gas.
2. **Inner Planets:** Mercury, Venus, Earth, and Mars are the four inner planets closest to the Sun.
3. **Outer Planets:** Jupiter, Saturn, Uranus, and Neptune are the four outer planets farthest from the Sun.
4. **Dwarf Planets:** Pluto, Eris, Ceres, Haumea, and Makemake are the five officially recognized dwarf planets in our solar system.

**The Eight Planets:**

1. **Mercury:** The smallest planet, closest to the Sun, with extremely high temperatures during the day and freezing temperatures at night.
2. **Venus:** The hottest planet, with a thick atmosphere that traps heat, making it inhospitable to life.
3. **Earth:** Our home planet, with a diverse range of environments and life forms.
4. **Mars:** A rocky planet with a thin atmosphere, considered a potential candidate for human habitation.
5. **Jupiter:** The largest planet, a gas giant with massive storms like the Great Red Spot.
6. **Saturn:** Another gas giant, known for its stunning ring system and numerous moons.
7. **Uranus:** An icy planet with a tilted axis that causes extreme seasons.
8. **Neptune:** The farthest planet from the Sun, with strong winds and massive storm systems.

**Other Celestial Objects:**

1. **Asteroids:** Small rocky objects in orbit around the Sun, found mostly in the asteroid belt between Mars and Jupiter.
2. **Comets:** Icy bodies that release gas and dust as they approach the Sun, creating spectacular tails of debris.
3. **Kuiper Belt:** A region beyond Neptune's orbit filled with small, icy bodies and other celestial objects.
4. **Oort Cloud:** A distant, spherical shell of icy bodies surrounding our solar system.

**Key Features:**

1. **Orbital Periods:** The time it takes for an object to complete one orbit around the Sun varies greatly between planets (e.g., Mercury's 88 Earth days vs. Neptune's 165 Earth years).
2. **Atmospheres:** Many planets have atmospheres, which can be thick or thin, and affect their surface temperatures.
3. **Moons:** Most planets have natural satellites (moons), some of which are large enough to be considered dwarf planets.

**Exploration and Research:**

The Solar System has been extensively explored through spacecraft, telescopes, and other scientific instruments. Ongoing and future missions aim to:

1. Explore Mars and the search for life beyond Earth.
2. Study the outer planets and their moons in greater detail.
3. Investigate asteroids and comets to better understand their origins.

This is a brief introduction to our amazing Solar System. There's still much to learn, and scientists continue to explore and unravel its secrets!

 

response = ollama.chat(

    model="llama3.2",

    messages=[

        {"role": "user", "content": "Tell me about the Solar System"}

    ]

)

 

This line calls the ollama.chat function, which sends a query to the Ollama API. The API processes the query using the specified model and returns the AI's response in the response variable. The response is typically a JSON object containing details of the conversation.

 

model="llama3.2"

Specifies the AI model to use for processing the query. In this case, it's "llama3.2".

 

messages=[...]

Defines the sequence of conversational messages. It takes a list of dictionaries, where each dictionary represents a single message in the conversation.

 

·      "role": Specifies who is speaking. The roles typically include:

o   "user": The person (or system) asking the question.

o   "assistant": The AI responding to the user.

 

·      "content": The actual text of the message. Here, the user asks, "Tell me about the Solar System".

 

 

Previous                                                    Next                                                    Home

Getting Started with the Python Ollama Library: A Quick Guide to Listing LLMs on Your System

Step 1: Install the Ollama Library

To begin, you need to install the Ollama library. Depending on your Python setup, you can use either pip or pip3:

pip install ollama
    (OR)
pip3 install ollama

This ensures the library is installed and ready to use.

 

Step 2: Writing Your First Script

Once the library is installed, you can create a Python script to list all the available LLMs in your system. Here's a simple example:

 

llmsInMySystem.py

import ollama

llmsInMySystem = ollama.list();
print(llmsInMySystem);

 

Step 3: Running the Script

Save the above code in a file named llmsInMySystem.py. Run the script using the following command.

python llmsInMySystem.py

 

If everything is set up correctly, the script will output a list of all the available LLMs on your system.

Output
models=[Model(model='llama3.2-vision:latest', modified_at=datetime.datetime(2025, 1, 18, 15, 21, 43, 518870, tzinfo=TzInfo(+05:30)), digest='085a1fdae525a3804ac95416b38498099c241defd0f1efc71dcca7f63190ba3d', size=7901829417, details=ModelDetails(parent_model='', format='gguf', family='mllama', families=['mllama', 'mllama'], parameter_size='9.8B', quantization_level='Q4_K_M')), Model(model='llama3.2:latest', modified_at=datetime.datetime(2025, 1, 17, 12, 26, 55, 61315, tzinfo=TzInfo(+05:30)), digest='a80c4f17acd55265feec403c7aef86be0c25983ab279d83f3bcd3abbcb5b8b72', size=2019393189, details=ModelDetails(parent_model='', format='gguf', family='llama', families=['llama'], parameter_size='3.2B', quantization_level='Q4_K_M'))]

 

ollama.list(): This function queries your system for all installed or accessible LLMs, returning their details in a structured format.

 

Let’s print the llms available in my system in a tablular format like below.

 

prettyPrintLlms.py

 

import ollama
from datetime import datetime

# Fetch the list of available LLMs
llms_in_my_system = ollama.list()

# Print the output in a table format
print(f"{'Model Name':<10} {'Modified At':<15} {'Digest':<20} {'Size (bytes)':<5} {'Parameter Size':<15} {'Quantization Level':<10}")
print("-" * 140)

for model in llms_in_my_system.models:
    model_name = model.model
    modified_at = model.modified_at.strftime("%Y-%m-%d %H:%M:%S")  # Format datetime
    digest = model.digest
    size = model.size
    parameter_size = model.details.parameter_size
    quantization_level = model.details.quantization_level

    print(f"{model_name:<20} {modified_at:<25} {digest:<40} {size:<15} {parameter_size:<15} {quantization_level:<20}")

Output

Model Name Modified At     Digest               Size (bytes) Parameter Size  Quantization Level
--------------------------------------------------------------------------------------------------------------------------------------------
llama3.2-vision:latest 2025-01-18 15:21:43       085a1fdae525a3804ac95416b38498099c241defd0f1efc71dcca7f63190ba3d 7901829417      9.8B            Q4_K_M              
llama3.2:latest      2025-01-17 12:26:55       a80c4f17acd55265feec403c7aef86be0c25983ab279d83f3bcd3abbcb5b8b72 2019393189      3.2B            Q4_K_M 

 

Previous                                                    Next                                                    Home

Why python3 Works but python Doesn’t (And How to Fix It)

Many Have you ever installed Python3.x on your computer, typed python in the terminal, and gotten a frustrating command not found error, only to realize python3 works just fine?

$python
bash: python: command not found
$
$python3
Python 3.12.8 (v3.12.8:2dc476bcb91, Dec  3 2024, 14:43:19) [Clang 13.0.0 (clang-1300.0.29.30)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>

 If this has happened to you, don’t worry, you’re not alone! This is a common issue, especially for beginners or developers.

Why Is There a Difference Between python and python3?

Back in the day, running python in the terminal would start Python 2, the older (now outdated) version of Python. When Python 3 was released, it introduced changes that weren’t fully compatible with Python 2. To avoid breaking existing scripts, most systems kept:

 

·      python for Python 2 installation

·      python3 for Python 3 installation

 

Over time, Python 2 was officially discontinued (as of 2020), and many modern systems now only install Python 3 by default, but they don’t always set up python as a shortcut. That’s why you might see:

 

·      python3 works (because it’s explicitly Python 3).

·      python fails (because the system doesn’t automatically link it to Python 3).

 

How to Make python Run Python 3?

If you want python to just work, create a simple alias to python3 command line tool. You can tell your terminal to treat python as python3 by adding an alias to your shell configuration file.

echo 'alias python=python3' >> ~/.bashrc && source ~/.bashrc

 

If you're on macOS and use ~/.bash_profile instead, replace .bashrc with .bash_profile

 

For Zsh (macOS default shell):

 

echo 'alias python=python3' >> ~/.zshrc && source ~/.zshrc

 

After running this, check that it works:

$python --version
Python 3.12.8
$
$python3 --version
Python 3.12.8

 

Now, python and python3 will do the same thing!

 

The difference between python and python3 is an old leftover from earlier versions, but it’s easy to deal with. If you want to use python in python3 installation, the easiest fix is to create an alias.

 

Previous                                                    Next                                                    Home

Monday, 21 April 2025

Adding Background Music and Sound Effects to your Kaplay Game

Adding an audio to your game can greatly enhance the player's experience. Kaplay simplifies this process by providing the methods to load, play, and control sound effects and background music. Let’s dive into how you can use Kaplay's powerful audio features to bring your game to life.

 

Loading Sounds

To use audio files in your game, you first need to load them using the loadSound() function.

This function requires two parameters:

a.   the name of the sound and

b.   the file path.

 

Here's an example,

const k = kaplay();
k.loadSound("jumpSound", "sounds/jump.mp3");

 

Now, the sound is ready to be played whenever needed in the game.

 

Playing Sounds

The play() function allows you to play any sound you've loaded. It supports various options through the AudioPlayOpt interface, making it easy to customize playback.

 

Here's how you can use it.

 

k.play("jumpSound", {
    volume: 0.5, // Plays the sound at 50% volume
    speed: 1.5,  // Plays the sound 1.5x faster
    loop: true,  // Loops the sound continuously
});

 

Advanced Sound Options

The AudioPlayOpt interface offers flexibility for sound customization. Here's a breakdown of its properties:

 

Property

Description

Example

paused

Starts audio paused if set to true.

{ paused: true }

loop

Repeats the sound after it ends.

{ loop: true }

volume

Sets audio volume (0.0 to 1.0).

{ volume: 0.75 }

speed

Adjusts playback speed (1.0 = normal).

{ speed: 2.0 }

detune

Changes pitch (100 = 1 semitone).

{ detune: 200 }

seek

Starts playback from a specific time (in seconds).

{ seek: 5 }

pan

Adjusts stereo position (-1.0 to 1.0).

{ pan: -0.5 }

 

Stopping Sounds

Every time you play a sound using the play() function, it returns an AudioPlay object. You can use this object to stop the sound or perform other actions.

 

For example,

const sound = k.play("jumpSound");
sound.stop(); // Stops the sound

 

Randomizing Sounds

Kaplay supports creative sound manipulation, such as randomizing pitch for dynamic effects. Here's an example:

k.play("noteC", {
    detune: Math.floor(Math.random() * 12) * 100, // Randomly detunes the sound
});

By mastering these audio features, you can transform your game into a more engaging experience. Whether it's adding a subtle background track or dynamic sound effects, Kaplay gives you the tools to create rich audio interactions.

 

Follow below step-by-step procedure to build a working application.

 

Step 1: Create a KAPLAY project add-sounds by executing below command.

 

npx create-kaplay add-sounds

  Upon successful execution of above command, you can see a project structure looks like below. 

 


Step 2: Update src/main.js file like below.

 

main.js

import kaplay from "kaplay";

// Initialize Kaplay
const k = kaplay();

// Set gravity for the game world
k.setGravity(1000);

// Load assets
k.loadRoot("./"); // Base path for assets (useful for publishing)
k.loadSprite("bean", "sprites/bean.png"); // Load the player sprite
k.loadSound("jumpSound", "sounds/jump.mp3"); // Load the jump sound

// Create the player object
const player = k.add([
  k.pos(120, 80), // Initial position
  k.sprite("bean"), // Use the "bean" sprite
  k.body(), // Enable physics
  k.area(), // Define collision area
]);

// Function to handle player jump
const handleJump = () => {
  k.play("jumpSound", {
    volume: 0.5, // Play sound at 50% volume
    speed: 1.5, // Play sound at 1.5x speed
  });
  player.jump(400); // Make the player jump
};

// Function to move the player
const handleMovement = (direction) => {
  const speed = 300; // Set the movement speed
  player.move(direction * speed, 0);
};

// Bind keys to actions
player.onKeyPress("space", handleJump); // Jump on spacebar press
player.onKeyDown("left", () => handleMovement(-1)); // Move left
player.onKeyDown("right", () => handleMovement(1)); // Move right

// Add the ground to the game world
k.add([
  k.rect(k.width(), 100), // Ground width spans the game width
  k.pos(0, 700), // Position at the bottom of the screen
  k.area(), // Define collision area
  k.outline(3), // Add an outline for visibility
  k.color(109, 99, 19), // Brown-like color for the ground
  k.body({ isStatic: true }), // Make the ground static
]);

// Notes:
// - Use `sound.stop()` to stop any playing sound if needed.

 

Step 3: Create sounds folder in public folder and add jump.mp3 file to it. You can download this file from this location.

 

Step 4: Execute below commands from project root folder to run the Application.

npm install
npm run dev

 

Launch the url ‘http://localhost:3001/’ in a browser to play with the Application.

 

You can see a demo recording here (https://www.youtube.com/watch?v=JsTjaMT7oxw)

 

You can download the Application from this link.



Previous                                                    Next                                                    Home