Using Text Generation to Decide

This tutorial takes a side step: instead of learning a policy from rewards, you let a Large Language Model (LLM) — a neural network trained on huge text corpora to predict and generate text (Wikipedia, 2026) — read the current game state and decide which action to take.

The same pipeline is reused throughout:

  1. A prompt describes the state.
  2. The model replies with text.
  3. A small parser turns that text into a valid game action.

Ollama, an LLM API Tool

A pre-trained LLM already encodes common-sense knowledge and some strategic patterns for well-known problems, so you can expect a working policy with almost no training data.

We use Ollama, a local runner for open-weight models. This tutorial requires:

  1. Creation of a free account on Ollama.
  2. A local installation: macOS / Linux / Windows instructions.

Ollama is a terminal-based solution. Here are some ollama commands:

Command Purpose
ollama -v Print the Ollama version.
ollama serve Start the local Ollama daemon/server.
ollama run <model> Run a model interactively (downloads it if missing).
ollama run <model> "prompt" One-shot prompt, useful in scripts.
ollama pull <model> Download a model's weights.
ollama ls List locally downloaded models.
ollama ps Show running models and their GPU/CPU placement.
ollama stop <model> Unload a running model from memory.
ollama rm <model> Delete a downloaded model.
ollama show <model> Display model metadata and parameters.
ollama signin Authenticate with your Ollama account.
ollama launch <harness> --model <model> Start a harness backed by a model.
/bye (in session) Exit the interactive chat.
/set parameter <name> <value> (in session) Tune sampling/context at runtime.

Run a Model Locally

A local model runs entirely on your own machine: no network, no account, no cost per call. Ollama downloads the weights once (ollama pull) and keeps them in a local store (default ~/.ollama/models). The first run may download the model if it is not already present.

Start an interactive session with the smallest recent Llama (~2GB model):

ollama run llama3.2

You are now in a chat loop. Type a prompt and press Enter; the model streams its answer back in the terminal. Type /bye to exit.

For a one-shot call (useful in scripts or to test a prompt):

ollama run llama3.2 "Hello, world"

On the first prompt the model has to be loaded; afterwards the response latency is considerably reduced. Ollama keeps the model loaded for a few minutes. The command ollama ps lets you list those ready-to-use models and how they are loaded (CPU vs. GPU).

Example output:

NAME          ID            SIZE    PROCESSOR    UNTIL
llama3:70b    bcfb190...    42 GB   100% GPU     4 minutes from now

Ollama gives you access to a large variety of open-weight models: ollama.com/search.

Run a Cloud Model

It is also possible to use Ollama with cloud models. Cloud models use the exact same CLI and API as local ones, so your code does not change — only the model name. With this architecture all your requests — and only your requests — go to a server somewhere on Earth.

Let us play, for instance, with gemma4:

ollama run gemma4:cloud

You will be asked to link your local Ollama to your ollama.com account.

The run environment lets users interact with the Ollama harness and the model configuration using \commands. For instance:

  • /? or /help — list the main commands.
  • /set parameter temperature 0.1 — tune sampling (see "Tune the Model").
  • /set parameter num_ctx 4096 — enlarge the context window.
  • /show info — inspect the model's metadata.
  • /bye — quit.

Example prompt:

ollama run gemma4:cloud "Explain Markov decision processes in one sentence."

First, we notice that most recent models include thinking mechanisms. Second, we can trace the consumption of tokens on the remote service: ollama.com/dashboard.

Tune the Model with Ollama

LLM models, including thinking mechanisms, can be controlled with parameters. They modify the possible responses in terms of quality, inventiveness, and the way they are produced, directly impacting latency.

Typically, inventiveness is controlled by temperature (and related sampling parameters). A low temperature (0.0–0.2) makes the model deterministic and repeatable; a high temperature makes it creative but erratic — bad for a game bot.

Other classical parameters relate to context definition, token selection hazards, etc.

Parameter Effect Typical value
temperature Creativity vs. determinism. 0.0–0.2 for a bot
num_ctx Context window size (input + output tokens). 2048–8192
top_p (nucleus) Keep tokens whose cumulative probability reaches p. 0.8–0.95
top_k Keep only the k most likely next tokens. 20–50
repeat_penalty Penalize tokens already generated (reduces loops). 1.0–1.2
presence_penalty / frequency_penalty Penalize reuse of tokens (less common in Ollama). 0.0–1.0
mirostat Adaptive sampling for stable perplexity. 0 (off) or 2
seed Fixed RNG seed for reproducible runs. any integer
stop Strings that end generation early (e.g. "\n"). list of strings
num_predict Max number of tokens to generate. -1 (unlimited) or a cap

The cleanest way to keep these settings is to bake them into a Modelfile.conf (Ollama's config file) and create a tuned model. It also lets you record some context elements via the SYSTEM parameter.

# Modelfile
FROM llama3.2
PARAMETER temperature 0.1
PARAMETER num_ctx 4096
PARAMETER top_p 0.9
PARAMETER top_k 40
PARAMETER repeat_penalty 1.1
PARAMETER seed 42
SYSTEM "You are a game player seeking the appropriate action to perform in a particular situation."

This way it is possible to build and use the tuned model:

ollama create player-llama -f Modelfile.conf
ollama run player-llama

Search a 421 Prompt

We identified and learned how to use an LLM toolbox. Let us now apply it to Py421.

The goal is to define a prompt that makes the model output a value you can parse directly — typically an action formatted as keep-keep-roll for the three dice of Py421. Try a few variants across several models with ollama run to identify an appropriate combination.

Prompt engineering is the practice of wording prompts so the model reliably produces the desired format (Wikipedia, 2026).

Compare: does it follow the format? Does it add explanations? Does it change with temperature? Write down the variant that works best and reuse it in code.

Tips - Be explicit about the output format and give one example. - Ask for "only" the answer, and nothing else. - Prefer short, structured prompts over long prose.

To notice that, some models are dedicated to decision, but exploring those solutions are out of the scope of this first tutorial. Also, not all cloud models are availlable in free subscription some interresting candidates are gemma4, beam.


Agent Harness Ollama

"An agent harness, also known as agent scaffolding, is the software infrastructure surrounding a large language model (LLM) that enables it to operate as an AI agent." Wikipedia, 2026.

In practice this means: code that calls the model, parses its answer, and feeds the result back to the game loop. Building this wrapper ("harness") is the core of this tutorial.

Typically it consists of using the Ollama Python API:

import ollama

prompt = "My beautiful tuned prompt"
response = ollama.generate(model="llama3.2", prompt=prompt)
print(response["response"])

Note that Ollama provides a chat() option in place of generate():

  • chat() (chat completion) — takes a list of messages with roles (system, user, assistant) and maintains a conversation context. Use it when you want multi-turn dialogue, role conditioning, or when the model is instruction-tuned to follow chat templates. The reply is response["message"]["content"].
  • generate() (non-chat completion, raw completion) — takes a single prompt string and continues it as plain text, with no implicit chat template. Use it for free-form text continuation, or when you format the whole prompt yourself. The reply is response["response"].

In practice, prefer chat() with a clear system/user split; fall back to generate() if you control the full prompt text.

For a chat completion:

response = ollama.chat(
    model="llama3.2",
    messages=[{"role": "user", "content": prompt}],
)
print(response["message"]["content"])

Agent Harness OpenAI

Alternatively to ollama, and mostly to access cloud model. It is possible to rely on the openai SDK to get access to any model trough any provider.

Using OpenRouter provider with a free model provided by NVidia the code will be :

from openai import OpenAI

# 1. Initialiser le client en remplaçant base_url
client = OpenAI(
    base_url="https://openrouter.ai/api/v1",
    api_key="sk-or-v1-5fyour-sdk-keyc7ac"
)

# 2. Appeler le modèle en utilisant le format "fournisseur/modèle"
completion = client.chat.completions.create(
    model="nvidia/nemotron-3-ultra-550b-a55b:free",  # Peut également être remplacé par d'autres modèles comme "mistralai/mistral-large"
    messages=[
        {"role": "user", "content": "Explique-moi en une phrase ce qu'est l'informatique quantique."}
    ]
)

print(completion.choices[0].message.content)

Agent Harness - Next-Step

We now need to extract the core component (the action to perform, in our case) from potentially verbose responses. For that we need regular expressions — patterns describing a set of strings (Wikipedia). The re module in Python provides regular expression matching operations: docs.python.org.

In our case the code looks like:

import re

def parse_action(text):
    match = re.search(r"(keep|roll)-(keep|roll)-(keep|roll)", text.lower())
    if match:
        return match.group(0)
    # Fallback when the model misbehaves:
    return "keep-keep-keep"

Test it on both clean and noisy outputs:

parse_action("keep-roll-roll")                       # -> "keep-roll-roll"
parse_action("I think you should keep-roll-roll.")  # -> "keep-roll-roll"
parse_action("no idea")                             # -> "keep-keep-keep"

Create a Bot for Py421

Last step: wrap the previous pieces in a Py421 player. The player stores the horizon and dice, builds a prompt from perceive, calls the model in decide, and parses the result.

Resource conception: an LLM-based bot needs more CPU/GPU and RAM than a classic policy table. Size your machine for the chosen model (see the Ollama GPU documentation and the GPU support notes) and budget latency headroom so the game loop never starves.

class LLMBot:
    def __init__(self, model="player-llama"):
        self._model = model
        self._horizon = None
        self._dice = None

    def wakeUp(self, playerId, numberOfPlayers, gameConf):
        self._state = "3-4-2-1"   # placeholder
        self._action = "keep-keep-keep"

    def perceive(self, gameState):
        self._horizon = gameState.child(1).digit(1)
        self._dice = gameState.child(2).digits()

    def decide(self):
        prompt = (
            f"Py421 state: horizon={self._horizon}, dice={self._dice}. "
            f"Choose keep or roll for each die. Answer ONLY as three words "
            f"joined by dashes, e.g. keep-roll-roll."
        )
        resp = ollama.chat(
            model=self._model,
            messages=[{"role": "user", "content": prompt}],
            options={"temperature": 0.1},
        )
        text = resp["message"]["content"]
        return parse_action(text)

    def sleep(self, finalState):
        pass

Try the solution in a few games, but not too many (or only with a local model): LLM -based AIs are not fast enough, and more importantly your tokens are precious.


Go Further — Open-Source Harnesses

Ollama comes with several open-source harnesses to connect with open-weight models.

  • OpenCode — a coding-focused harness you can drive from the terminal. It reads your repository, edits files, and runs commands, all backed by a chosen model. Useful here to generate and iterate on the Py421 bot, regression tests, and evaluation scripts.
  • Hermes — a general-purpose autonomous harness (the one this environment runs on). It keeps a long-lived agent loop, can delegate sub-tasks, and persists memory/skills across sessions. Useful for longer experiments that need state and reproducibility.
  • OpenClaw — an open-source harness exposing an OpenAI-compatible interface, handy for swapping providers without changing client code.

With ollama launch you can control which model a harness uses (and which backend it talks to):

ollama launch opencode --model gemma4:cloud

With OpenCode, you can ask for a test bench that validates decisions on obvious states are as expected. With the appropriate prompt, OpenCode generates a test_llm_decision.py file that you can process with pytest:

pytest test_llm_decision.py
# or
python -m pytest test_llm_decision.py

As an example, this tutorial was written with the help of Hermes coupled to a tuned gemma4:cloud model.