Wednesday, 2 April 2025

How to Use the /api/chat Endpoint for Conversations?

In this post, we'll explore how to effectively use the /api/chat endpoint for maintaining conversations with an AI assistant. Whether you're building a chatbot, virtual assistant, or interactive application, managing chat history and crafting structured requests are crucial for delivering a smooth user experience. We’ll dive into the request structure, provide practical examples, and share best practices for achieving conversational continuity.

The /api/chat endpoint is designed to handle interactive, context-aware conversations. By passing the conversation history along with each request, you can enable the AI model to respond naturally, maintaining context across multiple turns. This guide will walk you through how to structure your requests and manage chat history for effective interactions.

 

1. Understanding the Roles

The /api/chat endpoint uses the following roles to differentiate between parts of the conversation:

 

§  system: Provides initial instructions for the assistant's behaviour.

§  user: Represents messages from the user.

§  assistant: Represents responses from the AI assistant.

 

2. Starting a Conversation

To initiate a conversation, include a single user message in the messages array.

 

Example Request:

curl http://localhost:11434/api/chat -d '{
  "model": "llama3.2",
  "messages": [
    {
      "role": "user",
      "content": "What is the capital of India?"
    }
  ],
  "stream": false
}'

$curl http://localhost:11434/api/chat -d '{
>   "model": "llama3.2",
>   "messages": [
>     {
>       "role": "user",
>       "content": "What is the capital of India?"
>     }
>   ],
>   "stream": false
> }'

{"model":"llama3.2","created_at":"2025-01-18T06:22:11.304346Z","message":{"role":"assistant","content":"The capital of India is New Delhi."},"done_reason":"stop","done":true,"total_duration":318585334,"load_duration":29283459,"prompt_eval_count":32,"prompt_eval_duration":162000000,"eval_count":9,"eval_duration":126000000}

 

Formatted response looks like below.

{
  "model": "llama3.2",
  "created_at": "2025-01-18T06:22:11.304346Z",
  "message": {
    "role": "assistant",
    "content": "The capital of India is New Delhi."
  },
  "done_reason": "stop",
  "done": true,
  "total_duration": 318585334,
  "load_duration": 29283459,
  "prompt_eval_count": 32,
  "prompt_eval_duration": 162000000,
  "eval_count": 9,
  "eval_duration": 126000000
}

3. Continuing the Conversation

To maintain context, include the entire conversation history in subsequent requests.

 

Example Request:

curl http://localhost:11434/api/chat -d '{
  "model": "llama3.2",
  "messages": [
    {
      "role": "user",
      "content": "What is the capital of India?"
    },
    {
      "role": "assistant",
      "content": "The capital of India is New Delhi."
    },
    {
      "role": "user",
      "content": "Can you tell me a fact about New Delhi?"
    }
  ],
  "stream": false
}'

$curl http://localhost:11434/api/chat -d '{
>   "model": "llama3.2",
>   "messages": [
>     {
>       "role": "user",
>       "content": "What is the capital of India?"
>     },
>     {
>       "role": "assistant",
>       "content": "The capital of India is New Delhi."
>     },
>     {
>       "role": "user",
>       "content": "Can you tell me a fact about New Delhi?"
>     }
>   ],
>   "stream": false
> }'

{"model":"llama3.2","created_at":"2025-01-18T06:23:36.949495Z","message":{"role":"assistant","content":"New Delhi was the capital of British India from 1911 to 1947 and was designed by architects Edwin Lutyens and Herbert Baker in the early 20th century, with the intention of creating a grand and elegant city that would be a symbol of British colonial power."},"done_reason":"stop","done":true,"total_duration":1098513292,"load_duration":30183542,"prompt_eval_count":60,"prompt_eval_duration":185000000,"eval_count":57,"eval_duration":882000000}

 

Formatted response looks like below.

{
  "model": "llama3.2",
  "created_at": "2025-01-18T06:23:36.949495Z",
  "message": {
    "role": "assistant",
    "content": "New Delhi was the capital of British India from 1911 to 1947 and was designed by architects Edwin Lutyens and Herbert Baker in the early 20th century, with the intention of creating a grand and elegant city that would be a symbol of British colonial power."
  },
  "done_reason": "stop",
  "done": true,
  "total_duration": 1098513292,
  "load_duration": 30183542,
  "prompt_eval_count": 60,
  "prompt_eval_duration": 185000000,
  "eval_count": 57,
  "eval_duration": 882000000
}

 

4: Setting Assistant Behavior with system Role

Use the system role to guide the assistant's behavior.

 

For example:

curl http://localhost:11434/api/chat -d '{
  "model": "llama3.2",
  "messages": [
    {
      "role": "system",
      "content": "You are a helpful assistant who explains things simply and Expert in History"
    },
    {
      "role": "user",
      "content": "What is the Capital Of India"
    }
  ],
  "stream": false
}'

$curl http://localhost:11434/api/chat -d '{
>   "model": "llama3.2",
>   "messages": [
>     {
>       "role": "system",
>       "content": "You are a helpful assistant who explains things simply and Expert in History"
>     },
>     {
>       "role": "user",
>       "content": "What is the Capital Of India"
>     }
>   ],
>   "stream": false
> }'

{"model":"llama3.2","created_at":"2025-01-18T06:25:12.964391Z","message":{"role":"assistant","content":"The capital of India is New Delhi. However, it's worth noting that India has two capitals:\n\n1. **New Delhi**: This is the seat of the President of India and the official residence of the Prime Minister of India.\n2. **Rashtrapati Bhavan (Presidential Palace)**: Located in New Delhi, this is where the President of India lives.\n\nBut, if you're thinking of the administrative capital of India, it's:\n\n**Kolkata (West Bengal) for the state government**\nand \n**Pune for some state institutions**\n\nHowever, **New Delhi** remains the official capital city of India and is home to many important government institutions, embassies, and museums.\n\nWould you like to know more about India or its history?"},"done_reason":"stop","done":true,"total_duration":2592336416,"load_duration":28333750,"prompt_eval_count":44,"prompt_eval_duration":150000000,"eval_count":155,"eval_duration":2413000000}

Formatted response looks like below.

{
  "model": "llama3.2",
  "created_at": "2025-01-18T06:25:12.964391Z",
  "message": {
    "role": "assistant",
    "content": "The capital of India is New Delhi. However, it's worth noting that India has two capitals:\n\n1. **New Delhi**: This is the seat of the President of India and the official residence of the Prime Minister of India.\n2. **Rashtrapati Bhavan (Presidential Palace)**: Located in New Delhi, this is where the President of India lives.\n\nBut, if you're thinking of the administrative capital of India, it's:\n\n**Kolkata (West Bengal) for the state government**\nand \n**Pune for some state institutions**\n\nHowever, **New Delhi** remains the official capital city of India and is home to many important government institutions, embassies, and museums.\n\nWould you like to know more about India or its history?"
  },
  "done_reason": "stop",
  "done": true,
  "total_duration": 2592336416,
  "load_duration": 28333750,
  "prompt_eval_count": 44,
  "prompt_eval_duration": 150000000,
  "eval_count": 155,
  "eval_duration": 2413000000
}

 

5. Best Practices

§  Only include relevant parts of the conversation to optimize payload size.

§  Use the stream Parameter. Set "stream": false for a complete response in one payload. Set "stream": true for real-time responses split into chunks.

§  Structure Your Messages: Follow the role conventions (system, user, assistant) to ensure clarity.

 

The /api/chat endpoint provides a flexible way to build conversational AI systems. By including chat history and leveraging the system role, you can create engaging and contextually aware experiences. Try these examples to enhance your application's interactivity!

 

Previous                                                    Next                                                    Home

Scenes in Kaplay: A Guide to Dynamic Game Structure and Data Handling

In Kaplay, scenes are essential elements for structuring a game. They help organize the game flow and define different parts of your game, such as the main menu, the actual gameplay, and the game-over screen. Understanding how to create, navigate between, and pass data through scenes is crucial for building a well-organized and interactive game. This post will walk you through the basics of scenes in Kaplay, and how to use them effectively to build immersive and dynamic gaming experiences.

Creating a Scene

A scene is created by calling the scene() function and providing a name for the scene, followed by a callback function that contains the code for what should happen when the scene is active.

 

Here’s how to create a simple "game" scene:

const k = kaplay();

// Define the "start" scene
k.scene("start", () => {
  let startObject = k.add([
    k.text("Press SPACE to Start", { size: 50}),
    k.pos(500, 500),
  ]);

  startObject.color = k.rgb(255, 20, 150);

  // Listen for the SPACE key to start the game
  k.onKeyPress("space", () => {
    k.go("game");
  });
});

In the above example, we initialize the game with kaplay(), and then create a scene named "start". Within the callback function, we add a text object as part of the scene.

 

Changing Scenes

Once you've created multiple scenes, you need a way to transition between them. This is done with the go() function. The go() function allows you to switch from one scene to another by specifying the scene's name.

k.go("game");

 

This function will trigger the callback function of the scene named "game", bringing it to the foreground of the application.

 

Passing Data Between Scenes

One powerful feature of Kaplay’s scene system is its ability to pass data between scenes. This makes it possible to share important game variables like scores or levels as players transition between different scenes.

 

For instance, you can pass a score value from the current scene to the game scene.

scene("game", (score) => {
    add([text(score), pos(12, 12)]);
});

 

When calling the go() function, you can pass the score to the scene.

go("game", 100);  // Passes the score value of 100 to the "game" scene

Passing Multiple Parameters

If you need to pass more than one piece of data, you can bundle them into an object. This allows you to easily manage and send multiple variables to your scenes.

scene("game", ({ score, level }) => {
    add([text(`Score: ${score}`), pos(12, 12)]);
    add([text(`Level: ${level}`), pos(12, 24)]);
});

And when transitioning to this scene, you can pass the object containing both parameters.

go("game", { score: 100, level: 1 });  // Passes an object with score and level

Follow below steps to build a complete working application.

 

Step 1: Create a KAPLAY project scenes-hello-world by executing below command.

npx create-kaplay scenes-hello-world

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



Step 2: Update src/main.js with below content.

 

main.js

import kaplay from "kaplay";

let startTime = 0; // To track when the game starts

const k = kaplay({
  background: [135, 206, 250], // Light blue background (sky-like)
}); // Initialize the game

// Define the "start" scene
k.scene("start", () => {
  const startObject = k.add([
    k.text("Press SPACE to Start", { size: 50 }),
    k.pos(500, 500),
  ]);

  startObject.color = k.rgb(255, 20, 150);

  // Listen for the SPACE key to start the game
  k.onKeyPress("space", () => {
    startTime = Date.now(); // Record the start time
    k.go("game");
  });
});

// Define the "game" scene
k.scene("game", () => {
  // Add the player
  const player = k.add([
    k.rect(32, 32), // Draw a rectangle for the player
    k.pos(50, 50), // Initial position
    k.color(0, 0, 255), // Blue color
    k.area(), // Add collision detection
    "player", // Tag the player object
  ]);

  let counter = 0; // Track collected beans

  // Add 10 static beans (goal) at random positions
  for (let i = 0; i < 5; i++) {
    k.add([
      k.sprite("bean"), // Use a sprite for the bean
      k.pos(k.rand(0, k.width() - 32), k.rand(0, k.height() - 32)), // Random position
      k.area(), // Add collision detection for the bean
      "bean", // Tag the bean object
    ]);
  }

  // Add movement for the player
  k.onKeyDown("left", () => {
    player.move(-200, 0); // Move left
  });
  k.onKeyDown("right", () => {
    player.move(200, 0); // Move right
  });
  k.onKeyDown("up", () => {
    player.move(0, -200); // Move up
  });
  k.onKeyDown("down", () => {
    player.move(0, 200); // Move down
  });

  // Check for collision between player and beans
  k.onCollide("player", "bean", (player, bean) => {
    bean.destroy(); // Remove the bean when collected
    counter++;
    if (counter === 5) {
      const totalTime = Math.floor((Date.now() - startTime) / 1000); // Calculate elapsed time in seconds
      k.go("gameover", { totalTime }); // Go to the "gameover" scene when all beans are collected
    }
  });
});

// Define the "gameover" scene
k.scene("gameover", ({ totalTime }) => {
  const gameOverObject = k.add([
    k.text(
      `You collected all beans in ${totalTime} seconds! Press R to Restart`,
      {
        size: 40,
      }
    ),
    k.pos(100, 100),
  ]);

  gameOverObject.color = k.rgb(255, 20, 150);

  // Listen for the R key to restart the game
  k.onKeyPress("r", () => {
    k.go("start");
  });
});

// Load the bean sprite
k.loadRoot("./");
k.loadSprite("bean", "sprites/bean.png");

// Start the game at the "start" scene
k.go("start");

Step 3: 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=TYV52jNAOJ4).

 

You can download the Application from this link.


In summary, scenes are a fundamental concept in Kaplay that help to structure your game into logical sections. By using the scene() function, you can create different stages of your game, from menus to the gameplay screen, and even to the game-over screen. The ability to pass data between scenes with the go() function makes it easy to keep track of important game variables like scores, levels, and player progress.

 

Mastering scenes and data passing in Kaplay will allow you to create dynamic and interactive games that flow smoothly and respond to player actions in real-time.

 

Previous                                                    Next                                                    Home

Understanding Events and Event Handlers in KAPLAY

Events in KAPLAY provide a way to handle specific moments in your game execution by executing code when those moments occur. This guide covers the basics of events, event handlers, and their types, helping you implement dynamic game mechanics with ease.

 

What Are Events?

Events are actions or occurrences within the game, such as:

·       A player pressing a key

·       Clicking the mouse

·       An enemy being hurt

By responding to these events, you can make your game interactive and engaging.

 

Event Handlers

Event Handlers are methods that "listen" for events and execute code when the event occurs. These methods are typically named in the format on{EventName}.

 

Example

onKeyPress("space", () => { // Logic here });

 

Event Controller

When an event handler is created, it returns an Event Controller. This allows you to manage the event, such as canceling or pausing it.

 

Example

const pressEvent = onKeyPress((key) => { debug.log(key); }); pressEvent.cancel(); // Stops running the handler

 

Follow below step-by-step procedure to build an Application.

 

Step 1: Create a KAPLAY project event-handling-hello-world by executing below command.

 

npx create-kaplay event-handling-hello-world

 

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

 


 

Step 2: Update src/main.js with below code.

 

main.js

import kaplay from "kaplay";

const k = kaplay();

k.setGravity(1000);

k.loadSprite("bean", "sprites/bean.png");

const player = k.add([k.pos(120, 80), k.sprite("bean"), k.body(), k.area()]);

const ground = k.add([
  k.rect(k.width(), 100),
  k.pos(0, 700),
  k.area(),
  k.outline(3),
  k.color(109, 99, 19), // Brown-like color for the ground
  k.body({ isStatic: true }),
]);

// Function to create and fire a bullet
function fireBullet() {
  const bullet = k.add([
    k.pos(player.pos.x + player.width / 2 - 5, player.pos.y), // Position at player's top center
    k.circle(10), // Bullet size
    k.color(255, 0, 0), // Red bullet color
    k.area(),
  ]);

  // Move bullet upwards in the update loop
  bullet.onUpdate(() => {
    bullet.move(0, -400); // Move up with a speed of 600 units per second

    // Destroy the bullet if it goes off-screen
    if (bullet.pos.y < -10) {
      bullet.destroy();
    }
  });
}

// Event listener for space key press
player.onKeyPress("space", () => {
  if (player.isGrounded()) {
    fireBullet();
  }
});

// Define smooth horizontal movement for the player
// Move left when the left arrow key is held down
player.onKeyDown("left", () => {
  player.move(-300, 0); // Move left with a speed of 300
});

// Move right when the right arrow key is held down
player.onKeyDown("right", () => {
  player.move(300, 0); // Move right with a speed of 300
});

// Add screen boundaries to prevent the player from moving off the screen
player.onUpdate(() => {
  if (player.pos.x < 0) {
    player.pos.x = 0; // Prevent moving off the left edge
  }
  if (player.pos.x > k.width() - player.width) {
    player.pos.x = k.width() - player.width; // Prevent moving off the right edge
  }
});

 Step 3: 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=DM_KSBHkcfM).

 

 

Explanation of Code

Event handlers in KAPLAY are functions that "listen" for specific game events and execute code when those events occur. They are defined using methods like onKeyPress, onKeyDown, and onUpdate.

 

1. onKeyPress: Listens for a specific key press event and executes the associated code once when the key is pressed.

 

player.onKeyPress("space", () => {
    if (player.isGrounded()) {
        fireBullet();
    }
});

 

This handler listens for the space key press. If the player is grounded (standing on a surface), the fireBullet function is triggered, creating a bullet.

 

2. onKeyDown: Listens for a specific key being held down and executes the associated code repeatedly while the key is pressed.

player.onKeyDown("left", () => {
    player.move(-300, 0); // Move left
});

player.onKeyDown("right", () => {
    player.move(300, 0); // Move right
});

The left and right arrow keys are used to move the player horizontally. This creates smooth, continuous movement as long as the key is held.

 

3. onUpdate: Runs a callback function every frame, typically 60 times per second.

bullet.onUpdate(() => {
    bullet.move(0, -400); // Bullet moves upward
    if (bullet.pos.y < -10) {
        bullet.destroy(); // Remove bullet when it leaves the screen
    }
});

player.onUpdate(() => {
    if (player.pos.x < 0) {
        player.pos.x = 0; // Prevent moving off the left edge
    }
    if (player.pos.x > k.width() - player.width) {
        player.pos.x = k.width() - player.width; // Prevent moving off the right edge
    }
});

 

The bullet's onUpdate handler moves the bullet upwards every frame and destroys it when it goes off-screen. The player's onUpdate handler ensures the player stays within screen boundaries by restricting its x position.

 

You can download the Application from this link.

 

Previous                                                    Next                                                    Home