# BESSER Labs

Hands-on labs for the BESSER low-code platform. Online version: https://labs.besser-pearl.org/

1. [Draw your first class diagram](#lab-1) (40 min)
2. [Model in Python with B-UML](#lab-2) (1 h)
3. [Add behavior to your model](#lab-3) (50 min)
4. [Model by conversation with the Modeling Assistant](#lab-4) (35 min)
5. [From a description to a running app with the Spec-Driven Agent](#lab-5) (1 h 30 min)
6. [From a class diagram to a database](#lab-6) (50 min)
7. [Build a full web app from three models](#lab-7) (1 h 15 min)
8. [Publish your app to Render, then extend it](#lab-8) (45 min)
9. [Build agents with the BESSER Agentic Framework](#lab-9) (1 h 15 min)
10. [Personalize an agent for its users](#lab-10) (55 min)
11. [Write your own code generator](#lab-11) (1 h)
12. [Extend the B-UML metamodel and a generator](#lab-12) (1 h 30 min)

---

<a id="lab-1"></a>

## Lab 1: Draw your first class diagram

A class diagram of an academic research domain in the Web Modeling Editor, checked, turned into Python classes and backed up as a JSON file.

| Time | Level | Runs with | Do first | Track |
| --- | --- | --- | --- | --- |
| 40 min | Beginner | Browser | Nothing | Modeling foundations |

**You'll learn to**

- Create a project in the BESSER Web Modeling Editor
- Add classes with typed attributes
- Connect classes with associations, a composition and generalizations
- Define an enumeration and use it as an attribute type
- Check a model with Quality Check and generate Python code from it
- Back up a project as a JSON file and know where projects are stored

**You'll need**

- A modern browser (Chrome, Edge, Firefox or Safari)
- No account and no installation

**Files for this lab**

- [Finished model of this lab (project JSON)](https://labs.besser-pearl.org/files/first-model/research_lab.json)

Online version: https://labs.besser-pearl.org/labs/first-model/

---

In this lab you model a small academic research domain. Researchers write papers, papers are presented at research events, and an event is either a conference or a workshop. You draw it as a UML class diagram in the BESSER Web Modeling Editor, let the editor check it, and generate Python code from it.

You need no UML background. Each step introduces one concept: a class, an attribute, an association, a composition, a generalization and an enumeration. The same model comes back in the next labs, where you build it in Python and add behavior to it.

### 1. Open the editor and create a project

1. Open [https://editor.besser-pearl.org](https://editor.besser-pearl.org). On a first visit the editor asks how you want to build.
2. Under **Model it**, click **Start modelling**. The other card, **Describe it**, opens the AI assistant instead; you use it in a later lab.

![The first-visit screen with the Model it and Describe it cards](https://labs.besser-pearl.org/labs/first-model/interface-choice.png "Choose Model it: you draw the model yourself.")

3. The **Create A Project** form opens. Type `Research Lab` as **Name**. Leave **Owner** and **Description** as they are.
4. Under **View**, keep **Low-code**. Under **Modeling perspective**, choose **Data Modeler**. This perspective shows only the class and object diagrams, which is all you need here.
5. Click **Create Project**.

![The Create A Project form with the name Research Lab, Low-code and Data Modeler selected](https://labs.besser-pearl.org/labs/first-model/create-project.png "Low-code and Data Modeler: the canvas plus the class and object diagram editors.")

> **Before you continue**
>
> Projects are stored only in this browser (its local storage). Nothing is saved on a server. If you clear the site data, switch to another browser or use a private window, the project is gone. The last step of this lab shows how to export a backup file.

> **Check your work**
>
> The top bar shows the project name `Research_Lab` (spaces become underscores). The left sidebar lists **Class** and **Object**, and the **Class Diagram** tab shows a palette next to an empty canvas.

![An empty class diagram with the palette: two kinds of class, Enumeration, OCL Constraint and Comment](https://labs.besser-pearl.org/labs/first-model/empty-class-diagram.png "The palette. You drag elements from it onto the canvas.")

### 2. Add classes with typed attributes

A class describes a kind of thing in the domain. Its attributes are the data every instance of the class holds, each with a type such as `str` (text), `int` (whole number), `bool` (true or false) or `date`.

1. Drag the first palette element, the **Class** box with one attribute, onto the canvas.
2. Double-click the new class. A panel opens on the right.
3. In the name field at the top of the panel, replace `Class` with `Paper`.
4. Under **Attributes**, the class already has one attribute called `Attribute`. Rename it to `title`. Its type stays **str (string)**.
5. Click the empty field below it (it shows `+ attribute: str`), type `submitted: date` and press <kbd>Enter</kbd>. Then type `acceptance: bool` and press <kbd>Enter</kbd>. The text after the colon becomes the attribute type.
6. Close the panel with its **×** button or by clicking an empty spot on the canvas.

![The Paper class with title, submitted and acceptance, and its panel showing the three attributes with their types](https://labs.besser-pearl.org/labs/first-model/paper-class.png "Each attribute row has a visibility (+), a name and a type dropdown.")

Repeat this for two more classes, placed so there is room between them:

| Class | Attributes |
|---|---|
| `ResearchEvent` | `name: str`, `start: date`, `end: date` |
| `Researcher` | `name: str`, `institution: str` |

You can also change a type afterwards with the type dropdown in the attribute row, for example to **int (integer)** or **date**.

> **Note**
>
> B-UML names cannot contain spaces or hyphens. Use `ResearchEvent` or `research_event`, not `Research Event`.

> **Check your work**
>
> Three classes are on the canvas: `Paper` with three attributes, `ResearchEvent` with three and `Researcher` with two, each shown as `+ name: type`.

### 3. Connect papers and researchers with an association

An association says that instances of two classes are related. Here, a paper has one or more authors, and a researcher can write any number of papers. Those numbers are the multiplicities of the two ends.

1. Click `Paper` once to select it. Blue connection points appear around it.
2. Press on a connection point on the bottom edge of `Paper` and drag to `Researcher`. Release over `Researcher`. A line appears.
3. Double-click the line. The **Association** panel opens.
4. Set **Name** to `authorship`.
5. The panel has one section per end. In the **Paper** section, set **Multiplicity** to `*` and **Role** to `papers`. In the **Researcher** section, set **Multiplicity** to `1..*` and **Role** to `authors`.

![The authorship association between Paper and Researcher with its panel: Paper end * and role papers, Researcher end 1..* and role authors](https://labs.besser-pearl.org/labs/first-model/association-authorship.png "The role is the name of that end: a researcher reaches their papers through papers, a paper its authors through authors.")

Multiplicities are written as `min..max`: `1` means exactly one, `0..1` at most one, `*` any number, and `1..*` at least one.

> **Check your work**
>
> A line connects `Paper` and `Researcher`. It shows `papers` and `*` near `Paper`, and `authors` and `1..*` near `Researcher`.

### 4. Make events own their papers with a composition

A composition is a strong association: the part cannot exist without its whole. In this domain a paper belongs to exactly one event, and deleting the event deletes its papers.

1. Select `Paper`, then drag from a connection point on its left edge to `ResearchEvent`.
2. Double-click the new line. Set **Name** to `presented_at`.
3. In the **Paper** section, set **Multiplicity** to `*` and **Role** to `papers`. In the **ResearchEvent** section, set **Multiplicity** to `1` and **Role** to `event`.
4. Click the dropdown that shows **Association** and choose **Composition**.

![The presented_at composition with a filled diamond at ResearchEvent and the Composition panel](https://labs.besser-pearl.org/labs/first-model/composition-presented-at.png "The filled diamond sits at the whole (ResearchEvent). The part's Navigable box is locked, because a whole can always reach its parts.")

> **If something goes wrong**
>
> If the diamond appears at `Paper` instead of `ResearchEvent`, you drew the line in the other direction. Click the two-arrow button next to the bin icon at the top of the panel to swap the ends, then check the multiplicities again.

> **Check your work**
>
> A line with a filled black diamond at `ResearchEvent` connects it to `Paper`, labelled `event` / `1` and `papers` / `*`.

### 5. Add Conference and Workshop as kinds of ResearchEvent

A generalization says that one class is a special kind of another. A `Conference` is a `ResearchEvent`, so it inherits `name`, `start` and `end` and adds what is specific to it.

1. Add a class `Conference` with the attribute `acronym: str`, and a class `Workshop` with `topic: str`. Place both below `ResearchEvent`.
2. Select `Conference` and drag from a connection point on its top edge to `ResearchEvent`.
3. Double-click the line and change the dropdown from **Association** to **Generalization**. The panel title changes to **Generalization** and the name and multiplicity fields disappear.
4. Do the same from `Workshop` to `ResearchEvent`.

![Conference and Workshop connected to ResearchEvent by generalizations, with the Generalization panel open](https://labs.besser-pearl.org/labs/first-model/generalization.png "The hollow triangle points at the general class.")

> **Check your work**
>
> Two lines with hollow triangles point from `Conference` and `Workshop` up to `ResearchEvent`. If a triangle points at a subclass, swap the ends with the two-arrow button.

### 6. Add an enumeration for the event mode

An enumeration is a type with a fixed list of values, called literals. An event takes place in person, online or both.

1. Drag the **Enumeration** element from the palette onto the canvas and double-click it.
2. Rename it to `EventMode`. Under **Literals**, rename `Enum Value_1`, `Enum Value_2` and `Enum Value_3` to `in_person`, `online` and `hybrid`.

![The EventMode enumeration with the literals in_person, online and hybrid in its panel](https://labs.besser-pearl.org/labs/first-model/enumeration.png "In the panel, the Enumeration toggle is on: this classifier holds literals, not attributes.")

3. Double-click `ResearchEvent`, type `mode: EventMode` in the `+ attribute: str` field and press <kbd>Enter</kbd>. The enumeration is now available as a type, next to the built-in ones.

![The ResearchEvent panel with the new attribute mode of type EventMode](https://labs.besser-pearl.org/labs/first-model/enum-attribute.png "Enumerations appear in the attribute type dropdown.")

> **Check your work**
>
> `ResearchEvent` has four attributes, the last one `+ mode: EventMode`, and the `EventMode` box shows the stereotype «enumeration» above its name.

![The complete research model with five classes, one enumeration, an association, a composition and two generalizations](https://labs.besser-pearl.org/labs/first-model/research-model.png "The whole model at this point.")

### 7. Check the model and generate Python classes

1. Click **Quality Check** in the top bar (the round button with a check mark, left of the theme toggle). The editor converts the diagram to a B-UML model and validates it.

![A notification that says Diagram is valid](https://labs.besser-pearl.org/labs/first-model/quality-check-valid.png "A valid model. Errors are listed in the same place.")

2. Open **Generate > OOP > Python Classes**. The editor downloads a file called `classes.py`. No account or API key is needed.

![The Generate menu with Code Generation, OOP expanded and Python Classes and Java Classes](https://labs.besser-pearl.org/labs/first-model/generate-python.png "The menu lists the generators that fit the active diagram.")

3. Open `classes.py` in any editor. Each class became a Python class with typed constructor parameters, the generalization became inheritance, and each association end became a property that keeps both sides in sync:

```python
class EventMode(Enum):
    in_person = "in_person"
    online = "online"
    hybrid = "hybrid"

class Conference(ResearchEvent):

    def __init__(self, name: str, start: date, end: date, mode: EventMode, acronym: str, papers: set["Paper"] = None):
        super().__init__(name, start, end, mode, papers)
```

If you have Python 3 installed, you can try the classes. Save this next to `classes.py` as `try_classes.py` and run `python try_classes.py`:

```python
from datetime import date
from classes import Conference, EventMode, Paper, Researcher

models = Conference(name="MODELS 2026", start=date(2026, 10, 4), end=date(2026, 10, 9),
                    mode=EventMode.in_person, acronym="MODELS")
alice = Researcher(name="Alice", institution="LIST")
paper = Paper(title="Low-code for research software", submitted=date(2026, 4, 1),
              acceptance=True, authors={alice}, event=models)

print(paper.event.acronym, paper.event.mode)
print([p.title for p in alice.papers])
print([p.title for p in models.papers])
```

```text
MODELS EventMode.in_person
['Low-code for research software']
['Low-code for research software']
```

Setting the paper's authors and event also filled `alice.papers` and `models.papers`: the generated code keeps both ends of each association consistent.

> **Check your work**
>
> Quality Check shows "Diagram is valid", and `classes.py` contains the classes `EventMode`, `Researcher`, `ResearchEvent`, `Workshop`, `Paper` and `Conference`.

### 8. Back up the project as a JSON file

Because the project lives only in this browser, export it to a file you keep.

1. Open **File > Export Project**. The **Export Project** dialog opens.
2. Under **Multiple Diagrams**, keep **Class Diagram** ticked and click **Export as JSON**. The browser downloads `Research_Lab.json`.

![The Export Project dialog with Multiple Diagrams on the left and Current Diagram image exports on the right](https://labs.besser-pearl.org/labs/first-model/export-project.png "Export as JSON keeps the whole project. The right half exports the current diagram as SVG, PNG, JSON or B-UML.")

To restore the backup, in this or another browser, open **File > Import > Project file (.json / .py)** and select the file. Importing always creates a new project; it does not overwrite the open one.

> **Note**
>
> **Export as B-UML** writes the same model as a Python file that uses the B-UML library. The next lab, [Model in Python with B-UML](https://labs.besser-pearl.org/labs/buml-python/), starts from there.

> **Check your work**
>
> `Research_Lab.json` is in your downloads folder. You can compare it with the finished model of this lab, linked at the top of the page.

### 9. Exercise: add reviews with scores

> **Exercise: Add a Score class**
>
> Papers are reviewed before they are accepted. Extend the model so that:
>
> - a new class `Score` represents the score a paper receives from one reviewer;
> - a `Score` has at least two attributes: the score value and the reviewer's comments;
> - each `Paper` can have several scores, and each `Score` is given by exactly one `Researcher` acting as reviewer.
>
> Run **Quality Check** when you are done.

<details>
<summary>Show a solution</summary>

`Score` needs two associations: one to `Paper` (a paper has `*` scores, a score belongs to `1` paper; a composition fits, since a score has no meaning without its paper) and one to `Researcher` (multiplicity `1` on the researcher end, with the role `reviewer`). The value can be an `int` for now.

</details>

> **Exercise: Restrict the score value**
>
> Make sure the score value is always one of `strong_accept`, `accept`, `weak_accept`, `borderline`, `weak_reject` and `reject`. Check the model again and export a new JSON backup.

<details>
<summary>Show a solution</summary>

Add an enumeration, for example `ScoreValue`, with those six literals, and change the type of the value attribute from `int` to `ScoreValue` in its type dropdown.

</details>

For more on the class diagram editor, see the [class diagram guide](https://besser.readthedocs.io/projects/besser-web-modeling-editor/en/latest/user-guide/diagrams/class-diagram.html) and the [projects guide](https://besser.readthedocs.io/projects/besser-web-modeling-editor/en/latest/user-guide/projects.html).

---

Checked against BESSER 8.0 on 2026-10-02.


<a id="lab-2"></a>

## Lab 2: Model in Python with B-UML

The research domain written with the B-UML Python API, validated, turned into a SQLite database and a Django admin app, and moved between Python and the editor.

| Time | Level | Runs with | Do first | Track |
| --- | --- | --- | --- | --- |
| 1 h | Beginner | Python | [Lab 1](https://labs.besser-pearl.org/labs/first-model/) | Modeling foundations |

**You'll learn to**

- Build a domain model in Python with classes, attributes, associations, generalizations and an enumeration
- Validate a B-UML model and inspect it from code
- Generate SQLAlchemy code and create a SQLite database from it
- Generate and run a Django project with an admin interface
- Move a model from the editor to Python and back

**You'll need**

- Python 3.11 or 3.12
- A terminal and a code editor

**Files for this lab**

- [Research domain model (domain_model.py)](https://labs.besser-pearl.org/files/buml-python/domain_model.py)

Online version: https://labs.besser-pearl.org/labs/buml-python/

---

In [Draw your first class diagram](https://labs.besser-pearl.org/labs/first-model/) you drew the research domain in the editor. Every editor model is a B-UML model underneath, and B-UML is also a Python library. In this lab you build the same model in Python, which is how you script models, test them, or plug BESSER into your own tools.

You then hand the model to two code generators: SQLAlchemy, which gives you a database, and Django, which gives you a web app with an admin interface. At the end you move a model from the editor into Python and the other way around.

### 1. Install BESSER in a virtual environment

1. Create a folder for this lab, for example `buml-lab`, and open a terminal in it.
2. Create and activate a virtual environment, then install BESSER:

```bash
python -m venv venv
source venv/bin/activate
python -m pip install besser
```

```powershell
python -m venv venv
venv\Scripts\activate
python -m pip install besser
```

3. Check the installed version:

```bash
python -c "from importlib.metadata import version; print(version('besser'))"
```

```text
8.0.1
```

> **If something goes wrong**
>
> If the version command prints 6.x or older, your Python is older than 3.11 and pip quietly installed the last release that supports it. BESSER 8 needs Python 3.11 or newer. Check with `python --version`, install 3.11 or 3.12, and create the virtual environment again with that interpreter.

> **Check your work**
>
> The version command prints `8.0.1` (or a later 8.x release), and your prompt shows `(venv)`.

### 2. Define the classes and their attributes

Download [domain_model.py](https://labs.besser-pearl.org/files/buml-python/domain_model.py) into your lab folder and open it. It builds the model from the first lab. The first part creates the enumeration and the classes:

```python
from besser.BUML.metamodel.structural import (
    BinaryAssociation, BooleanType, Class, DateType, DomainModel, Enumeration,
    EnumerationLiteral, Generalization, Multiplicity, Property, StringType,
)

# Enumeration
EventMode = Enumeration(name="EventMode", literals={
    EnumerationLiteral(name="in_person"),
    EnumerationLiteral(name="online"),
    EnumerationLiteral(name="hybrid"),
})

# Classes and their attributes
Researcher = Class(name="Researcher", attributes={
    Property(name="name", type=StringType),
    Property(name="institution", type=StringType),
})

Paper = Class(name="Paper", attributes={
    Property(name="title", type=StringType),
    Property(name="submitted", type=DateType),
    Property(name="acceptance", type=BooleanType),
})

ResearchEvent = Class(name="ResearchEvent", attributes={
    Property(name="name", type=StringType),
    Property(name="start", type=DateType),
    Property(name="end", type=DateType),
    Property(name="mode", type=EventMode),
})

Conference = Class(name="Conference", attributes={Property(name="acronym", type=StringType)})
Workshop = Class(name="Workshop", attributes={Property(name="topic", type=StringType)})
```

Each attribute is a `Property` with a name and a type. The primitive types are ready-made objects: `StringType`, `IntegerType`, `FloatType`, `BooleanType`, `DateType`, `DateTimeType`, `TimeType`, `TimeDeltaType` and `AnyType`. An enumeration is used as a type in the same way, as `mode` shows.

> **Note**
>
> Older tutorials import `String` or `Integer`. Those names do not exist in BESSER 8; use `StringType`, `IntegerType` and so on.

> **Check your work**
>
> `domain_model.py` is in your lab folder, and you can find the five classes and the `EventMode` enumeration in it.

### 3. Connect the classes and group them in a domain model

The second part of the file adds the relationships and wraps everything in a `DomainModel`:

```python
# Associations: each end is a Property named after the role it plays.
authorship = BinaryAssociation(name="authorship", ends={
    Property(name="papers", type=Paper, multiplicity=Multiplicity(0, "*")),
    Property(name="authors", type=Researcher, multiplicity=Multiplicity(1, "*")),
})

# Composition: an event owns its papers (is_composite goes on the whole's end).
presented_at = BinaryAssociation(name="presented_at", ends={
    Property(name="papers", type=Paper, multiplicity=Multiplicity(0, "*")),
    Property(name="event", type=ResearchEvent, multiplicity=Multiplicity(1, 1), is_composite=True),
})

# Generalizations: a Conference is a ResearchEvent, and so is a Workshop.
conference_is_event = Generalization(general=ResearchEvent, specific=Conference)
workshop_is_event = Generalization(general=ResearchEvent, specific=Workshop)

# The domain model groups everything.
domain_model = DomainModel(
    name="Research_Lab",
    types={Researcher, Paper, ResearchEvent, Conference, Workshop, EventMode},
    associations={authorship, presented_at},
    generalizations={conference_is_event, workshop_is_event},
)
```

A `BinaryAssociation` has exactly two ends. Each end is a `Property` whose `type` is the class at that end and whose name is the role, the same values you typed in the editor's **Role** fields. `Multiplicity(0, "*")` is the editor's `*`, and `Multiplicity(1, "*")` is `1..*`.

Run the file. Its last lines print every class with its own attributes:

```bash
python domain_model.py
```

```text
Conference(acronym: str)
Paper(acceptance: bool, submitted: date, title: str)
ResearchEvent(end: date, mode: EventMode, name: str, start: date)
Researcher(institution: str, name: str)
Workshop(topic: str)
```

> **Check your work**
>
> The command prints the five classes above, without errors.

### 4. Validate the model and inspect it

B-UML checks some rules as you build the model and others when you ask for a full validation. Create `inspect_model.py` next to `domain_model.py`:

```python
from domain_model import domain_model, Conference

result = domain_model.validate(raise_exception=False)
print("valid:", result["success"], "errors:", result["errors"], "warnings:", result["warnings"])

print("Conference inherits from:", [p.name for p in Conference.parents()])
print("Conference attributes:", sorted(a.name for a in Conference.all_attributes()))

for assoc in sorted(domain_model.associations, key=lambda a: a.name):
    for end in sorted(assoc.ends, key=lambda e: e.name):
        m = end.multiplicity
        upper = "*" if m.max == 9999 else m.max
        print(f"{assoc.name}: {end.name} -> {end.type.name} [{m.min}..{upper}]"
              f"{' (composite)' if end.is_composite else ''}")
```

```bash
python inspect_model.py
```

```text
valid: True errors: [] warnings: []
Conference inherits from: ['ResearchEvent']
Conference attributes: ['acronym', 'end', 'mode', 'name', 'start']
authorship: authors -> Researcher [1..*]
authorship: papers -> Paper [0..*]
presented_at: event -> ResearchEvent [1..1] (composite)
presented_at: papers -> Paper [0..*]
```

`all_attributes()` includes the inherited ones, so `Conference` has `name`, `start`, `end` and `mode` from `ResearchEvent`. B-UML stores an unbounded upper multiplicity (`*`) as 9999.

Rules that are checked immediately raise an error at the line that breaks them. For example, names cannot contain spaces:

```python
Class(name="Research Event")
```

```text
ValueError: 'Research Event' is invalid. Name cannot contain spaces.
```

Marking both ends of an association with `is_composite=True` fails the same way, with `ValueError: The composition attribute cannot be tagged at both ends`.

> **Check your work**
>
> `inspect_model.py` prints `valid: True` and lists both ends of both associations, with `event` marked as composite.

### 5. Generate a SQLite database with SQLAlchemy

[SQLAlchemy](https://www.sqlalchemy.org/) maps Python classes to database tables. The BESSER generator writes that mapping for you. Create `generate_sql.py`:

```python
from besser.generators.sql_alchemy import SQLAlchemyGenerator
from domain_model import domain_model

SQLAlchemyGenerator(model=domain_model).generate(dbms="sqlite")
```

```bash
python generate_sql.py
```

```text
Code generated successfully!
```

The generator writes `output/sql_alchemy.py`. Run that file from inside `output` to create the database:

```bash
cd output
python sql_alchemy.py
cd ..
```

The script creates `output/data/Research_Lab.db` (the file is named after the model). To see the tables, create `show_tables.py` in the lab folder:

```python
import sqlite3

con = sqlite3.connect("output/data/Research_Lab.db")
for (table,) in con.execute("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name"):
    columns = [row[1] for row in con.execute(f"PRAGMA table_info('{table}')")]
    print(f"{table}: {', '.join(columns)}")
```

```bash
python show_tables.py
```

```text
authorship: authors, papers
conference: id, acronym
paper: id, title, submitted, acceptance, event_id
researcher: id, name, institution
researchevent: id, name, start, end, mode, type_spec
workshop: id, topic
```

Read the result against the model:

- Every class got a table with a generated `id` primary key.
- The many-to-many association `authorship` became a link table with one column per end.
- The composition `presented_at` became the foreign key `paper.event_id`, because a paper has exactly one event.
- The generalization became joined tables: `conference` and `workshop` hold only their own columns and share the `id` of a `researchevent` row, whose `type_spec` column records which subclass the row is.

You can also use the generated classes directly. Save this as `output/add_data.py` and run it from inside `output`:

```python
from datetime import date
from sqlalchemy.orm import Session
from sql_alchemy import engine, Conference, EventMode, Paper, Researcher

with Session(engine) as session:
    models = Conference(name="MODELS 2026", acronym="MODELS", start=date(2026, 10, 4),
                        end=date(2026, 10, 9), mode=EventMode.in_person)
    alice = Researcher(name="Alice", institution="LIST")
    paper = Paper(title="Low-code for research software", submitted=date(2026, 4, 1),
                  acceptance=True, event=models, authors=[alice])
    session.add(paper)
    session.commit()
    for p in session.query(Paper).all():
        print(p.title, "|", p.event.name, "|", [a.name for a in p.authors])
```

```text
Low-code for research software | MODELS 2026 | ['Alice']
```

> **Note**
>
> `dbms` also accepts `postgresql`, `mysql`, `mssql`, `mariadb` and `oracle`. The generated file then contains a placeholder connection string for that database, which you override with the `DATABASE_URL` environment variable, and you install the database driver yourself. See the [SQLAlchemy generator documentation](https://besser.readthedocs.io/en/latest/generators/alchemy.html).

> **Check your work**
>
> `show_tables.py` lists the six tables above, and `add_data.py` prints one paper with its event and author.

### 6. Generate and run a Django project

[Django](https://www.djangoproject.com/) is a Python web framework. The BESSER Django generator creates a complete project whose admin interface lets you create, edit and delete instances of every class. Create `generate_django.py`:

```python
from besser.generators.django import DjangoGenerator
from domain_model import domain_model

DjangoGenerator(
    model=domain_model,
    project_name="research_site",
    app_name="research_app",
    containerization=False,
).generate()
```

```bash
python generate_django.py
```

The script prints a line ending in `Django project generation completed successfully!` and creates the folder `research_site` with `manage.py`, `requirements.txt`, the project package `research_site` and the app `research_app`.

> **If something goes wrong**
>
> On Windows, if the script stops with `UnicodeEncodeError: 'charmap' codec can't encode character '✅'`, the console cannot print the check-mark character in the success message (this happens, for example, when the output is redirected). Run it as `python -X utf8 generate_django.py`, or set the environment variable `PYTHONIOENCODING=utf-8` first, and generate again. This is fixed in the next BESSER release after 8.0.1.

Install the project's dependencies and create its database. `requirements.txt` pins its own Django version, so it may replace the one BESSER installed in your virtual environment; that is expected.

```bash
cd research_site
python -m pip install -r requirements.txt
python manage.py makemigrations
python manage.py migrate
```

`makemigrations` reads the generated models:

```text
Migrations for 'research_app':
  research_app\migrations\0001_initial.py
    + Create model ResearchEvent
    + Create model Researcher
    + Create model Conference
    + Create model Workshop
    + Create model Paper
```

Create an admin account (it asks for a user name, an e-mail address and a password), then start the server:

```bash
python manage.py createsuperuser
python manage.py runserver
```

Open [http://127.0.0.1:8000/admin/](http://127.0.0.1:8000/admin/) and log in with the account you just created.

![The Django admin dashboard of research_site listing Conferences, Papers, ResearchEvents, Researchers and Workshops](https://labs.besser-pearl.org/labs/buml-python/django-admin-home.png "Every class of the model has an admin page with Add and Change.")

Add a conference, a researcher and a paper through the admin. In the generated `research_app/models.py`, `authorship` became a `ManyToManyField` and `presented_at` a `ForeignKey` with `on_delete=models.CASCADE`, so the paper form requires authors and an event, and deleting an event deletes its papers, as the composition says. Stop the server with <kbd>Ctrl+C</kbd>.

> **Check your work**
>
> The admin dashboard lists the five model classes under `Research_App`, each with **Add** and **Change**.

### 7. Move models between the editor and Python

**From the editor to Python.** In the editor, open the project from the first lab and choose **File > Export Project**, then **Export as B-UML**. The editor downloads `research_lab_project.py`. It is plain B-UML code, built with the same classes you used above, and it ends with a `Project` that holds the domain model:

```python
domain_model = DomainModel(
    name="Class_Diagram",
    types={ResearchEvent, Paper, Researcher, Conference, Workshop, EventMode},
    associations={authorship, presented_at},
    generalizations={gen_Conference_ResearchEvent, gen_Workshop_ResearchEvent},
    metadata=None
)
```

The domain model is named after the diagram tab (`Class Diagram`, with the space replaced). Put the file in your lab folder and use it like your own model. Create `from_editor.py`:

```python
from besser.generators.sql_alchemy import SQLAlchemyGenerator
from research_lab_project import domain_model

print(domain_model.name, sorted(c.name for c in domain_model.get_classes()))
SQLAlchemyGenerator(model=domain_model, output_dir="editor_output").generate(dbms="sqlite")
```

```text
Class_Diagram ['Conference', 'Paper', 'ResearchEvent', 'Researcher', 'Workshop']
Code generated successfully!
```

**From Python to the editor.** Open **File > Import > Project file (.json / .py)**.

![The File menu with Import expanded: Project file (.json / .py), From Spreadsheet and From GitHub](https://labs.besser-pearl.org/labs/buml-python/import-menu.png "Import always creates a new project.")

In the **Import A Project** dialog, drop `domain_model.py` on the drop zone or click it to browse. A plain model file works: it does not need a `Project` definition.

![The Import A Project dialog with a drop zone for JSON or Python project files](https://labs.besser-pearl.org/labs/buml-python/import-project-dialog.png "Supported formats: .json and .py.")

The editor converts the file, shows the notification `Imported project "Imported Project".` and opens the class diagram. It places the classes automatically, so drag them around until the diagram is readable.

![The research model imported from domain_model.py, with the classes laid out automatically](https://labs.besser-pearl.org/labs/buml-python/imported-model.png "The automatic layout overlaps some lines; move the classes to tidy it.")

> **Note**
>
> The editor does not run your file as a normal Python program. The server reads it with a restricted loader made for model-building code, so keep model files to model definitions. `domain_model.py`, including its printing code at the end, imports without changes.

> **Check your work**
>
> `from_editor.py` prints `Class_Diagram` and the five class names, and the editor shows a new project with the five classes and the `EventMode` enumeration from `domain_model.py`.

### 8. Exercise: junior and senior researchers

> **Exercise: Specialise Researcher**
>
> Researchers come in two kinds: `Junior` researchers, who have a supervisor, and `Senior` researchers, who have an h-index. Add both to `domain_model.py` as subclasses of `Researcher`, each with one attribute of a sensible type. Validate the model, generate the SQLAlchemy code again and recreate the database. Which new tables appear, and which columns do they have?

<details>
<summary>Show a solution</summary>

Create the two classes like `Conference`, add them to the `types` of the domain model, and add two `Generalization(general=Researcher, specific=...)` objects to its `generalizations`. You can also call `domain_model.add_type(...)` and `domain_model.add_generalization(...)` on the existing model. Delete `output/data/Research_Lab.db` before running `sql_alchemy.py` again. The database then has the tables `junior` and `senior` next to `researcher`.

</details>

> **Exercise: Reviews in Python**
>
> Add the `Score` class and the `ScoreValue` enumeration from the exercise of the first lab, this time in Python, and check that `validate()` still succeeds.

<details>
<summary>Show a solution</summary>

`ScoreValue` is an `Enumeration` with six `EnumerationLiteral`s. `Score` needs two `BinaryAssociation`s: one to `Paper` (put `is_composite=True` on the `Paper` end) and one to `Researcher` with a `reviewer` end of multiplicity `Multiplicity(1, 1)`.

</details>

The full API is described in the [structural model documentation](https://besser.readthedocs.io/en/latest/buml_language/model_types/structural.html), and the generators in the [Django generator documentation](https://besser.readthedocs.io/en/latest/generators/django.html).

---

Checked against BESSER 8.0 on 2026-10-02.


<a id="lab-3"></a>

## Lab 3: Add behavior to your model

The research model gains an OCL constraint, method bodies in BAL and Python and a state machine, and you watch them run in a generated FastAPI backend.

| Time | Level | Runs with | Do first | Track |
| --- | --- | --- | --- | --- |
| 50 min | Intermediate | Browser, Python | [Lab 1](https://labs.besser-pearl.org/labs/first-model/) | Modeling foundations |

**You'll learn to**

- Write an OCL invariant and check it with Quality Check
- Test a constraint against concrete objects in an object diagram
- Implement methods in the BESSER Action Language (BAL) and in Python
- Link a state machine to a method as its implementation
- Generate a FastAPI backend and call the modeled methods from Swagger UI

**You'll need**

- A modern browser
- Python 3.11 or 3.12 to run the generated backend (the modeling part needs only the browser)
- The project from the first lab, or the starter file below

**Files for this lab**

- [Starter project (JSON)](https://labs.besser-pearl.org/files/behavior/research_lab.json)

Online version: https://labs.besser-pearl.org/labs/behavior/

---

A class diagram describes structure: which data exists and how it is connected. Real systems also have rules and behavior. A paper has a page limit, an accepted paper must be marked as accepted, a review goes through stages. In this lab you add all three kinds to the research model from [Draw your first class diagram](https://labs.besser-pearl.org/labs/first-model/): an OCL constraint, methods with real bodies, and a state machine.

Then you generate a backend from the model and run it. The constraint becomes input validation, and each method becomes an HTTP endpoint you can call.

### 1. Open the research project and add a page count

1. In the [editor](https://editor.besser-pearl.org), open your `Research_Lab` project from the first lab. If you do not have it, download the [starter project](https://labs.besser-pearl.org/files/behavior/research_lab.json) and open **File > Import > Project file (.json / .py)** to import it.
2. Double-click `Paper` and add the attribute `pages: int` in the `+ attribute: str` field.

> **Check your work**
>
> `Paper` has four attributes: `title`, `submitted`, `acceptance` and `pages: int`.

### 2. Write an OCL constraint

OCL (Object Constraint Language) states rules that every valid instance must satisfy. An invariant is a rule about one class: `context <Class> inv <name>: <boolean expression>`, where `self` is the instance being checked.

1. Drag **OCL Constraint** from the palette onto the canvas, next to `Paper`, and double-click it.
2. In the **OCL Constraint** field, type:

```text
context Paper inv page_limit: self.pages <= 12
```

3. In **Description (shown to end-users when validation fails) Optional**, type `A paper can have at most 12 pages.` This text is the message people see when the rule is broken.

![The OCL Constraint panel with the invariant page_limit and its description, next to the Paper class](https://labs.besser-pearl.org/labs/behavior/ocl-constraint.png "The note on the canvas shows the stereotype «inv» and the start of the expression.")

4. Click **Quality Check**.

![The notification Valid Constraints, listing Paper inv page_limit with its description, followed by Diagram is valid](https://labs.besser-pearl.org/labs/behavior/quality-check-class.png "Quality Check parses the constraint against the classes and attributes of the diagram.")

> **Note**
>
> The editor reads the class from the `context` part of the text. You can draw a line from the note to `Paper` to document the link, but the line is only visual. Write `context Paper` exactly like that: some older examples write `Context "Person"`, with quotes, which the parser does not read as a class name.

> **Check your work**
>
> Quality Check lists `[Paper inv page_limit]` under **Valid Constraints** and reports "Diagram is valid".

### 3. Test the constraint on an object diagram

Quality Check on a class diagram only checks that the constraint is well formed. To see it judge data, you build concrete objects in an object diagram.

1. Click **Object** in the left sidebar. The palette lists one object per class of your class diagram, such as `paper_1 : Paper` and `researcher_1 : Researcher`. The **References** bar at the top shows which class diagram the objects come from.
2. Drag `paper_1 : Paper` onto the canvas and double-click it. Set `title` to `Low-code for research software`, pick a date for `submitted`, type `false` for `acceptance` and `15` for `pages`.

![The paper_1 object with pages = 15 and its Object panel with one field per attribute](https://labs.besser-pearl.org/labs/behavior/object-paper-15.png "Each attribute of the class gets a value field of the right kind: text, a date picker, true or false.")

3. Drag `researcher_1 : Researcher` below it and give it a name and an institution. Drag `conference_1 : Conference` next to it and fill in its name, dates and acronym.
4. A paper needs an author and an event, as the multiplicities say. Select `paper_1` and drag from one of its connection points to `researcher_1`. Double-click the new link, open the dropdown that shows **No Association** and choose `authorship`.

![The object link between paper_1 and researcher_1 with its panel set to the authorship association](https://labs.besser-pearl.org/labs/behavior/object-link-authorship.png "A link is an instance of an association. Choosing the association also fills in the link name.")

5. Link `paper_1` to `conference_1` the same way and choose `presented_at`.

![The object diagram with paper_1 linked to researcher_1 and to conference_1](https://labs.besser-pearl.org/labs/behavior/object-diagram.png "Three objects and two links. Conference objects also show the attributes inherited from ResearchEvent.")

6. Click **Quality Check**. The constraint is now evaluated against `paper_1`:

![The notification Invalid Constraints: Paper inv page_limit, Constraint violation: A paper can have at most 12 pages.](https://labs.besser-pearl.org/labs/behavior/quality-check-object-violation.png "The description you wrote is the explanation.")

7. Double-click `paper_1`, change `pages` to `10` and run **Quality Check** again.

![The notification Valid Constraints: Paper inv page_limit evaluates to True, followed by Diagram is valid](https://labs.besser-pearl.org/labs/behavior/quality-check-object-ok.png "The same rule, now satisfied.")

> **If something goes wrong**
>
> If Quality Check reports `Object 'paper_1' violates multiplicity 1..* for association end 'authors' of association 'authorship' (found 0 links)`, a link is missing or has no association. Double-click each link and check that its **Association** dropdown shows `authorship` or `presented_at`, not **No Association**.

> **Check your work**
>
> With `pages = 15`, Quality Check reports a constraint violation with your description. With `pages = 10`, it reports "Diagram is valid".

### 4. Implement methods in BAL

The BESSER Action Language (BAL) is a small, statically typed language for method bodies. Its syntax resembles Java and Python: `def name(param: type) -> return_type { ... }`, `this` for the current object, `if (...) { ... } else { ... }`, statements ending in `;`. The [BAL overview](https://besser.readthedocs.io/en/latest/besser_action_language/overview.html) lists everything else.

1. Click **Class** in the sidebar and double-click `Paper`.
2. Under **Methods**, type `+ length_class(): str` in the `+ method(param: str): str or →` field and press <kbd>Enter</kbd>.
3. Below the new method, open the **Type:** dropdown, which shows **None (UML)**, and choose **BESSER Action Language**. A code editor opens with a template that starts with `def length_class() -> nothing {`.
4. Replace the whole template with:

```text
def length_class() -> str {
    if (this.pages > 8) {
        return "long";
    } else {
        return "short";
    }
}
```

![The Paper panel with length_class implemented in BAL: the type dropdown shows BESSER Action Language and the editor holds the method body](https://labs.besser-pearl.org/labs/behavior/bal-method.png "The signature field is now read from the code and greyed out.")

5. Add a second method with a parameter. Type `+ reading_time(pages_per_hour: int): float`, choose **BESSER Action Language**, and replace the template with:

```text
def reading_time(pages_per_hour: int) -> float {
    return this.pages * 1.0 / pages_per_hour;
}
```

BAL checks types. `this.pages / pages_per_hour` divides two `int` values and is an `int`, which does not match the declared `float`; the generator then stops with `A return statement in function reading_time is returning an invalid type, returns int rather than float`. Multiplying by `1.0` first makes the expression a `float`.

> **If something goes wrong**
>
> If Quality Check reports `Invalid return type 'nothing' for the method 'length_class'`, the template is still in the code editor, above or instead of your code. The signature is taken from the first `def` line, so delete everything except your function.

> **Check your work**
>
> `Paper` shows `+ length_class(): str` and a `reading_time` method on the canvas, and Quality Check still reports "Diagram is valid". Long signatures are cut off on the canvas; the panel shows them in full.

### 5. Add a Python method that changes the paper

A method can also be written in Python. You use it here for a method that changes the object.

1. In the `Paper` panel, add `+ accept(): bool`.
2. Set its **Type:** to **Python Code** and replace the template with:

```python
def accept(self):
    """Mark the paper as accepted."""
    self.acceptance = True
    return self.acceptance
```

![The accept method with Type Python Code and its Python implementation](https://labs.besser-pearl.org/labs/behavior/python-method.png "Python methods take self and change the object directly.")

> **Note**
>
> In BESSER 8.0.x (checked on the public editor on 2 October 2026), the generated backend runs BAL bodies that read attributes and parameters and compute a result, like the two above. BAL bodies that assign to an attribute (`this.acceptance = true;`) fail when called on a paper, because `Paper` has associations: the call returns code 500 with `validation errors for PaperCreate ... Input should be a valid integer`. Navigating an association does not work yet either: `this.authors.size()` returns the text `<coroutine object BAL_size ...>` instead of a number. Use Python for those methods until this is fixed.

![The class diagram with pages added to Paper, its three methods, and the page_limit OCL note](https://labs.besser-pearl.org/labs/behavior/class-diagram-behavior.png "The model so far: one invariant and three implemented methods.")

> **Check your work**
>
> `Paper` lists three methods. In the panel, `length_class` and `reading_time` have the type **BESSER Action Language** and `accept` has **Python Code**.

### 6. Link a state machine to a method

A method can also be implemented by a state machine. The Data Modeler perspective hides state machines, so turn them on first.

1. Click **Settings** in the sidebar. Under **Modeling Perspectives**, tick **State Machine Diagram**. A **State** entry appears in the sidebar.

![The Modeling Perspectives list in Settings with State Machine Diagram ticked](https://labs.besser-pearl.org/labs/behavior/settings-state-machine.png "Turning a perspective off hides it from the sidebar but keeps its models.")

2. Click **State**. From the palette, drag an initial node (the filled circle), two **State** elements and a final node (the circle with a ring) onto the canvas. Double-click the states and name them `Submitted` and `Reviewed`.
3. Connect them from left to right: select an element and drag from one of its connection points to the next one.

![A state machine: initial node, Submitted, Reviewed and final node, connected by transitions](https://labs.besser-pearl.org/labs/behavior/state-machine.png "A minimal review process. Transitions can carry events and conditions; you can leave them empty here.")

4. Go back to **Class**, double-click `Paper` and add `+ review()`. Set its **Type:** to **State Machine**. A second dropdown appears; choose **State Machine Diagram**, the name of the state machine's tab.

![The review method with Type State Machine and the State Machine Diagram selected](https://labs.besser-pearl.org/labs/behavior/method-state-machine.png "The method now refers to the state machine diagram.")

> **Note**
>
> State machines have no generator of their own: with a state diagram active, the **Generate** menu says "State machines are used as method implementations in Class Diagrams. Generate code from the Class Diagram." The deterministic backend generator does not turn a state machine into code yet. The next step shows what `review` does in the generated backend.

> **Check your work**
>
> The sidebar shows **State**. The state diagram has four nodes and three transitions, and `review()` in `Paper` has the type **State Machine**.

### 7. Generate the backend and call the methods

1. With the class diagram active, open **Generate > Web > Full Backend**. The editor downloads `backend_output.zip`.

![The Generate menu with Web expanded: Django Project, Spring Project, Full Backend and Web Application](https://labs.besser-pearl.org/labs/behavior/generate-full-backend.png "Full Backend: a FastAPI application with SQLAlchemy and Pydantic.")

2. Unzip it into a new folder. It contains `main_api.py`, `routers/`, `pydantic_classes.py`, `sql_alchemy.py`, `database.py`, `bal_stdlib.py` and `requirements.txt`. Open a terminal in that folder, create and activate a virtual environment as in [Model in Python with B-UML](https://labs.besser-pearl.org/labs/buml-python/), then install and start the server:

```bash
python -m pip install -r requirements.txt
uvicorn main_api:app --reload
```

3. Open [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs). Swagger UI lists every endpoint. The methods are under **Paper Methods**:

![Swagger UI section Paper Methods with POST endpoints for accept, length_class and reading_time](https://labs.besser-pearl.org/labs/behavior/swagger-paper-methods.png "One POST endpoint per modeled method: /paper/{paper_id}/methods/<name>/.")

4. Create the data. In Swagger UI, open an endpoint, click **Try it out**, paste the body and click **Execute**. Create a conference with `POST /conference/`, then a researcher with `POST /researcher/`:

```json
{"name": "MODELS 2026", "start": "2026-10-04", "end": "2026-10-09", "mode": "in_person", "acronym": "MODELS"}
```

```json
{"name": "Alice", "institution": "LIST"}
```

5. Try to create a paper that breaks the page limit with `POST /paper/`:

```json
{"title": "Too long", "submitted": "2026-04-01", "acceptance": false, "pages": 15, "authors": [1], "event": 1}
```

The server answers with code 422. Your OCL invariant became a validator in `pydantic_classes.py`:

```json
{"detail":[{"type":"value_error","loc":["body","pages"],"msg":"Value error, pages must be <= 12","input":15,"ctx":{"error":{}},"url":"https://errors.pydantic.dev/2.6/v/value_error"}]}
```

6. Send the same body with `"title": "Low-code for research software"` and `"pages": 10`. This time you get code 200 and a paper with `"id": 1`.
7. Call the methods on paper 1. For `POST /paper/{paper_id}/methods/length_class/`, enter `1` as `paper_id` and execute:

![The Swagger response of length_class for paper 1: status executed and result long](https://labs.besser-pearl.org/labs/behavior/swagger-length-class.png "The BAL body ran on the stored paper, which has 10 pages.")

For `reading_time`, send the parameter inside `params`:

```json
{"params": {"pages_per_hour": 4}}
```

```json
{"paper_id":1,"method":"reading_time","status":"executed","result":"2.5","output":null}
```

Then call `accept` with an empty body (`{}`) and read the paper back with `GET /paper/{paper_id}/`:

```json
{"paper":{"id":1,"acceptance":true,"event_id":1,"pages":10,"title":"Low-code for research software","submitted":"2026-04-01"},"researcher_ids":[1]}
```

8. Finally, call `POST /paper/{paper_id}/methods/review/`. It answers with code 501 and `Method 'review' of Paper is modeled but has no implementation - 501, never a fake success`: the endpoint exists because the method is in the model, but its state machine is not translated into code.

> **If something goes wrong**
>
> If `uvicorn` is not found, the virtual environment is not active or `pip install -r requirements.txt` did not run in it. Activate it and install again. If port 8000 is taken, start the server with `uvicorn main_api:app --reload --port 8001` and use that port in the browser.

> **Check your work**
>
> Creating a paper with 15 pages returns 422 with `pages must be <= 12`, `length_class` returns `long`, `reading_time` returns `2.5`, and after `accept` the paper shows `"acceptance": true`.

The data is stored in SQLite, in `data/Class_Diagram.db` inside the backend folder; delete that file to start with an empty database. Stop the server with <kbd>Ctrl+C</kbd>.

### 8. Exercise: more rules and more behavior

> **Exercise: An event cannot end before it starts**
>
> Add an invariant to `ResearchEvent` that requires the end date to be on or after the start date. Generate the backend again and try to create a conference whose `end` is before its `start`.

<details>
<summary>Show a solution</summary>

The expression compares two attributes of the same object: `context ResearchEvent inv dates_in_order: self.end >= self.start`. The generated backend then rejects such an event with code 422 and `Constraint 'dates_in_order' violated: self.end >= self.start`. Because `Conference` inherits from `ResearchEvent`, the rule applies to conferences and workshops too.

</details>

> **Exercise: Does the paper fit a limit?**
>
> Add a BAL method `fits(limit: int): bool` to `Paper` that returns whether the paper has at most `limit` pages. Call it from Swagger UI with two different limits.

<details>
<summary>Show a solution</summary>

The body is a single `return` of a comparison between `this.pages` and the parameter. Send the parameter as `{"params": {"limit": 8}}`. Remember that BAL statements end with `;`.

</details>

Further reading: [OCL in B-UML](https://besser.readthedocs.io/en/latest/buml_language/model_types/ocl.html), [the BESSER Action Language](https://besser.readthedocs.io/en/latest/besser_action_language.html), the [object diagram guide](https://besser.readthedocs.io/projects/besser-web-modeling-editor/en/latest/user-guide/diagrams/object-diagram.html) and the [backend generator](https://besser.readthedocs.io/en/latest/generators/backend.html).

---

Checked against BESSER 8.0 on 2026-10-02.


<a id="lab-4"></a>

## Lab 4: Model by conversation with the Modeling Assistant

A clinic appointment model with a class diagram, an OCL constraint and a state machine, built and checked entirely through the Modeling Assistant chat.

| Time | Level | Runs with | Do first | Track |
| --- | --- | --- | --- | --- |
| 35 min | Beginner | Browser | Nothing | Build with AI |

**You'll learn to**

- Start a project in the Describe it (agentic) interface
- Create a class diagram from a plain-language description
- Refine a model with follow-up prompts and revert an assistant edit
- Verify what the assistant changed on the canvas and with Quality Check
- Add a state machine and trigger a code generator from the chat

**You'll need**

- A modern desktop browser (Chrome, Edge or Firefox)
- No modeling experience (the lab explains what you see on the canvas)

Online version: https://labs.besser-pearl.org/labs/modeling-assistant/

---

This is the lab to start with if you want to build software with BESSER without learning modeling first. The Web Modeling Editor has an agentic interface: you describe what you want in plain words, and the Modeling Assistant creates and edits the diagrams for you on a live canvas. Those diagrams are the model BESSER generates code from, so you only need to read them, not draw them. If you later want to draw them yourself, [Lab 1](https://labs.besser-pearl.org/labs/first-model/) shows how, and you can switch between chatting and drawing at any time.

In this lab you model a small clinic: patients book appointments with doctors. You build the class diagram by conversation, refine it, add a rule, add a state machine for the appointment lifecycle, and generate a PostgreSQL schema, all from the chat. Throughout, you check the result yourself instead of trusting the reply.

> **Note**
>
> The assistant runs on a separate BESSER service. On [editor.besser-pearl.org](https://editor.besser-pearl.org) it is hosted for you and needs no API key or account; requests are rate limited per browser tab. Your messages and a snapshot of the current project are sent to that service so it can answer. The project itself stays in your browser's storage. Do not paste personal or confidential data into the chat.

### 1. Start a project in Describe it mode

1. Open [https://editor.besser-pearl.org](https://editor.besser-pearl.org). On a first visit the editor asks how you want to build.
2. On the **Describe it** card, click **Start describing**.

![The first-run screen with two cards, Model it and Describe it, and a Free hosted Qwen pill on the Describe it card](https://labs.besser-pearl.org/labs/modeling-assistant/interface-choice.png "Describe it opens the agentic workspace; Model it opens the canvas you used in Lab 1")

3. The **Create A Project** form opens with **Agentic** already selected under **View**. Enter the name `Clinic Appointments` and click **Create Project**. The editor stores it as `Clinic_Appointments`.

![The Create A Project form with the name field, owner, description and the View toggle set to Agentic](https://labs.besser-pearl.org/labs/modeling-assistant/create-project-agentic.png "Agentic is preselected because you came from Describe it")

4. The assistant workspace fills the screen with the question "What would you like to create today?" and a composer that reads "Describe what you want to create or modify...". Next to the subtitle a dot shows the connection state.

![The assistant workspace with the headline, a Connected indicator, the composer and three example prompts](https://labs.besser-pearl.org/labs/modeling-assistant/describe-workspace.png "Green Connected means the hosted assistant is reachable. The example prompts under the composer change between visits")

> **Note**
>
> If the editor opens straight into the canvas (because you ticked "Remember my choice" earlier, or already have projects), use **File > New Project**, choose **Agentic** under **View**, and create the project there. Adding `?mode=agent` to the editor URL also opens the assistant workspace.

> **Check your work**
>
> The top bar shows the project name `Clinic_Appointments`, the workspace says **Connected** with a green dot, and the line under the composer reads "Free to use with our hosted Qwen model."

### 2. Describe the clinic and let the assistant build the class diagram

1. Click into the composer, type the following prompt exactly, and press <kbd>Enter</kbd>:

```text
Create a class diagram for a clinic appointment system with the classes Patient, Doctor and Appointment. A patient can book many appointments, and each appointment is with exactly one doctor. Give each class a few attributes.
```

2. Wait for the reply. It usually arrives within 20 to 30 seconds. The assistant marks it with a **System created** badge, summarises what it built ("Your ClinicAppointmentSystem spec is ready — it captures Patient, Doctor, Appointment, with 2 relationship(s) linking them.") and offers three quick-action chips under it: **Generate application**, **Explain the specs** and **Review the model**.

![The chat with the clinic prompt, a System created badge, the reply naming Patient, Doctor, Appointment and AppointmentStatus, and the three chips Generate application, Explain the specs and Review the model](https://labs.besser-pearl.org/labs/modeling-assistant/assistant-create-reply.png "The badge says what kind of change the assistant made. The chips appear under its latest reply")

> **Note**
>
> The wording of the reply, the attribute names and the layout differ from run to run, because a language model writes them. In one run the assistant added an `AppointmentStatus` enumeration, in another it added methods such as `cancel()`, and it often gives `Appointment` a `durationMinutes` attribute without being asked. That is expected. What you check in this lab is the model, not the text: which classes, attributes and associations exist on the canvas.

> **If something goes wrong**
>
> **The reply says "I had a bit of trouble building everything at once, but I set up 3 item(s)..." and each class only has `+ id: str`.** The assistant fell back to placeholder classes because its language-model call failed on the server. The same happens if every follow-up returns "I couldn't process that modification. Please try again or rephrase your request." This is a service problem, not a problem with your prompt. Wait a few minutes and click **New Chat** to try again, or continue the lab on the canvas: add the attributes and associations by hand as shown in [Lab 1](https://labs.besser-pearl.org/labs/first-model/), then come back to the chat for the later steps.

> **Check your work**
>
> The chat shows your prompt, a reply naming Patient, Doctor and Appointment, and at least the **Review the model** chip.

### 3. Switch to the canvas and verify what the assistant built

The assistant edits the model you see on the canvas. Look at the canvas after every change.

1. Click the **Review the model** chip. It does not send a message; it closes the assistant workspace so you see the canvas. You can also click the **See the Specs** tab at the bottom of the workspace, or press <kbd>Esc</kbd>.
2. The Class editor shows the new diagram. Check:
   - There are three classes: `Patient`, `Doctor` and `Appointment`, each with several typed attributes.
   - There is an association between `Patient` and `Appointment` with a many end (`*` or `0..*`) on the Appointment side.
   - There is an association between `Appointment` and `Doctor` with multiplicity `1` on the Doctor side.
3. Double-click an association to open its properties and read the exact multiplicities. The automatic layout sometimes draws two association ends on top of each other, so their role names overlap; drag a class to separate them.

> **New to class diagrams?**
>
> Each box is a **class**: a kind of thing your application stores, such as a patient. The lines inside the box are its **attributes**, the data kept for each one, written `name: type` (for example `+ birth_date: date`). A line between two boxes is an **association**: the things are related. The numbers at each end are **multiplicities**. They say how many: `1` means exactly one, `*` or `0..*` means any number. So `Appointment 0..*` next to `Patient 1` reads "a patient has any number of appointments, and each appointment belongs to exactly one patient". That is all you need to read what the assistant builds.

![The class diagram the assistant built: Patient, Doctor and Appointment with typed attributes, an AppointmentStatus enumeration, and two associations with 1 at the Patient and Doctor ends and 0..* at the Appointment end](https://labs.besser-pearl.org/labs/modeling-assistant/clinic-class-diagram.png "Read the multiplicities: patient 1 and doctor 1 at the top, 0..* at the Appointment end. Here the two Appointment-side role names overlap")

4. To return to the chat, click the **Describe your app** tab at the top of the canvas. The conversation is still there. In the low-code view the same assistant is also available from the round assistant button in the bottom-right corner (**Open assistant**); both share one conversation.
5. In the workspace's bottom bar, click **Your model**. It opens a recap of the data model and its relationships, derived from the project. Click it again to close it.

> **Check your work**
>
> You can move between chat and canvas with **Describe your app** and **See the Specs**, and the canvas shows the three classes connected by two associations with the multiplicities from your prompt. If a multiplicity is wrong, note it; you fix it in the next step.

### 4. Refine the model with follow-up prompts

Small, specific prompts work best. Name the class and the attribute, and say what must stay unchanged.

1. Send:

```text
Add an integer attribute named duration_minutes to the Appointment class.
```

2. Send:

```text
Rename the Doctor class to Physician.
```

   Each edit gets a **Modified** badge and a one-line reply, for example "Added attribute to Appointment." or "Updated Doctor."
3. Close the workspace and check both edits on the canvas: `Appointment` has `+ duration_minutes: int`, and the class formerly called `Doctor` is now `Physician`, still connected to `Appointment`. If the class already had a `durationMinutes` attribute, the assistant may rename that one instead of adding a second ("Updated attribute in attribute durationMinutes from Appointment."), or leave it unchanged. Make sure `Appointment` ends up with exactly one duration attribute, named `duration_minutes`; if not, ask for it again by name.
4. Revert the rename. <kbd>Ctrl+Z</kbd> on the canvas undoes your own canvas edits, but it does not undo changes the assistant made, so ask for the reverse change instead:

```text
Rename the Physician class back to Doctor.
```

   The reply reads "Updated Physician." Check on the canvas that the class is called `Doctor` again and that both associations are still there.
5. Add a rule. The assistant only writes OCL when you ask for a constraint explicitly:

```text
Add a constraint that the duration_minutes of an Appointment must be greater than 0.
```

6. The reply reads "Added OCL constraint on Appointment." On the canvas, an OCL constraint box marked `«inv»` is attached to `Appointment` by a dashed line. The box shows only the start of the expression (`context Appointment ...`); double-click it to read the whole text. It should be equivalent to `context Appointment inv: self.duration_minutes > 0`. In one run it read `context Appointment inv duration_must_be_positive: self.duration_minutes > 0`; the constraint name and exact formatting may differ.

![The Appointment class with duration_minutes: int and an OCL constraint box marked inv, connected to the class by a dashed line](https://labs.besser-pearl.org/labs/modeling-assistant/appointment-constraint.png "The constraint box is collapsed to its first words. Double-click it to read the full OCL expression")

> **Check your work**
>
> `Appointment` has `duration_minutes: int`, the class is named `Doctor` again, and an OCL constraint on `Appointment` requires `duration_minutes` to be greater than 0.

### 5. Ask the assistant to explain the model

The assistant can describe the current model in words. This is a quick way to spot a misunderstanding, but it is a summary, not a check.

1. Send:

```text
Describe my current model.
```

2. Compare the description with the canvas. The reply is headed "Current model" and lists each class with its attributes, the two associations and their role names, and usually the new constraint. It also summarises the other diagrams in the project (for example "GUI Diagram: A Home page with no sections."). It may mention "an association from ocl_... to Appointment": that is the dashed line linking the constraint box to its class, not an extra relationship. If the description and the canvas disagree, the canvas is the truth: the description is generated text, the canvas is the model that generators read.
3. The **Explain the specs** chip (shown after a model is created) sends a similar request for a plain-language overview.

> **Check your work**
>
> The reply describes patients, doctors and appointments and how they relate, and nothing in it contradicts what you see on the canvas.

### 6. Add a state machine by chat

The assistant can add a diagram of another type to the same project. Here you model the lifecycle of an appointment.

1. Send:

```text
Create a state machine for the appointment lifecycle with the states Requested, Confirmed, Completed and Cancelled.
```

2. The reply has a **System created** badge and reads like "Built the AppointmentLifecycle state machine with 6 state(s): Requested, Confirmed, Completed, Cancelled, connected by 13 transition(s)." The six states include an initial and a final node; the number of transitions varies between runs. The assistant adds a **State Machine Diagram** and switches the canvas to it. Close the workspace: the **State** editor is now highlighted in the left sidebar.
3. Check that the four states exist, that there is an initial state, and that the transitions make sense (for example Requested to Confirmed, Confirmed to Completed, and transitions to Cancelled). The assistant also gives each state `entry`, `do` and `exit` actions and writes guards on the transitions. Transition names are chosen by the assistant and vary, and long transition labels often overlap; drag the states apart or zoom in to read them.
4. If a state is missing, ask for it by name, for example `Add a NoShow state to the state machine, reachable from Confirmed.`

![The appointment state machine: an initial node, the states Requested, Confirmed, Cancelled and Completed with entry, do and exit actions, a final node, and many guarded transitions whose labels overlap](https://labs.besser-pearl.org/labs/modeling-assistant/appointment-state-machine.png "All four requested states are there. The overlapping transition labels are the assistant's automatic layout; drag the states to tidy it")

> **Note**
>
> The assistant supports eight of the nine diagram types: class, object, state machine, agent, user, GUI, quantum circuit and BPMN. Neural network diagrams are not supported, and the assistant button is hidden while a Neural Net diagram is open.

> **Check your work**
>
> The sidebar **State** editor contains a state machine with the states Requested, Confirmed, Completed and Cancelled, and the **Class** editor still contains your class diagram.

### 7. Validate the model and generate code from the chat

1. Click **Class** in the left sidebar so the class diagram is active.
2. Click **Quality Check** (the check-mark button in the top bar). Resolve any reported errors before you generate. Because the model has a constraint, a message titled "Valid Constraints:" lists it (for example `[Appointment inv duration_must_be_positive] 'context Appointment inv duration_must_be_positive: self.duration_minutes > 0'`) and stays open until you close it; a second, short-lived message reads "Diagram is valid". Quality Check validates the model; it says nothing about generated code.
3. Open the chat again and send:

```text
Generate SQL schema for PostgreSQL
```

4. The assistant runs the same SQL DDL generator as **Generate > Database > SQL DDL**, with the PostgreSQL dialect taken from your sentence. Within about 15 seconds a compact result card appears: **Generated deterministically** · `sql` · **0 tokens**, with **Show steps** and a **Download** button, followed by "Your code is generated and ready to download." The deterministic generators need no API key, use no language-model tokens, and give the same output for the same model.
5. Click **Download**. Nothing is saved until you click; the browser then saves `tables.sql` and the button changes to **Download again**.
6. Open `tables.sql` in a text editor. It starts with `-- Generated by BESSER 8.0.1`. Check that it contains a `CREATE TABLE` statement for each class (`patient`, `doctor`, `appointment`), a `duration_minutes INTEGER NOT NULL` column, and the foreign keys `FOREIGN KEY(doctor_id) REFERENCES doctor (id)` and `FOREIGN KEY(patient_id) REFERENCES patient (id)` in the appointment table. If your model has an enumeration such as `AppointmentStatus`, PostgreSQL gets a `CREATE TYPE ... AS ENUM` statement for it.

![The chat after the SQL request: a Generated deterministically card with sql, 0 tokens, Show steps and Download again, and the reply Your code is generated and ready to download](https://labs.besser-pearl.org/labs/modeling-assistant/assistant-sql-reply.png "0 tokens: the SQL came from BESSER's deterministic generator, not from the language model. The button reads Download again after the first download")

> **Note**
>
> Other inline generator requests follow the same pattern, for example `generate django backend with project name "clinic" and app name "appointments"` or `generate python`. Requests for a whole application ("generate the web app") are different: after a confirmation they start the Spec-Driven Agent, which uses a language model to build an app on top of the generators. That is the subject of the [next lab](https://labs.besser-pearl.org/labs/spec-driven-agent/).

> **If something goes wrong**
>
> **No result card appears, or the assistant replies with a list of generators ("What would you like me to generate? Here are the available options...").** The request was not recognised as a specific generator. Reply with the generator name it lists, for example `generate sql`, or use **Generate > Database > SQL DDL** and pick **PostgreSQL** in the dialog. If the browser blocked the download, allow downloads for the editor site.

> **Check your work**
>
> Quality Check reports the class diagram as valid, and you have a downloaded SQL file whose `CREATE TABLE` statements match the classes on the canvas.

### 8. Exercise: extend the clinic by conversation

> **Exercise: Add prescriptions and keep the model consistent**
>
> Using only the chat, add a `Prescription` class that belongs to exactly one appointment (an appointment can have several prescriptions), with a medication name and a dosage. Then add a constraint that a prescription's dosage must not be empty. Verify every change on the canvas, run Quality Check, and export the project with **File > Export Project** as a JSON backup.

<details>
<summary>Show a solution</summary>

Two short prompts work better than one long one: first create the class and its association, then add the constraint. On the canvas, check that the association end on the Prescription side is many and on the Appointment side is `1`. A constraint such as `context Prescription inv: self.dosage <> ''` is one valid form.

</details>

> **Exercise: Compare chat and canvas**
>
> Rebuild the same three-class clinic model by hand on the canvas in a second project, following [Lab 1](https://labs.besser-pearl.org/labs/first-model/). Export both projects as B-UML (**File > Export Project**, then **Export as B-UML**) and compare the two Python files. Which differences come from the assistant's choices (names, types, multiplicities) and which are only layout?

<details>
<summary>Show a solution</summary>

Layout is not part of the B-UML export, so any difference you find in the files is a modeling decision. Typical differences are attribute types (`str` versus `date` for a date), an extra identifier attribute, and the role names on association ends.

</details>

---

Checked against BESSER 8.0 on 2026-10-02.


<a id="lab-5"></a>

## Lab 5: From a description to a running app with the Spec-Driven Agent

A generated full-stack web app for a small event-ticketing model, downloaded, run on your machine, and optionally pushed to GitHub and reopened for further changes.

| Time | Level | Runs with | Do first | Track |
| --- | --- | --- | --- | --- |
| 1 h 30 min | Intermediate | Browser, Docker, GitHub | [Lab 4](https://labs.besser-pearl.org/labs/modeling-assistant/) | Build with AI |

**You'll learn to**

- Start a Spec-Driven Agent run from a reviewed model with an explicit request
- Choose between the keyless free tier and your own API key, and cap the cost of a run
- Read the run card, its phases, the scaffold badge and the verification findings
- Download the generated application and run it locally
- Iterate on the generated app and continue from a GitHub repository

**You'll need**

- A modern desktop browser
- Lab 4 (Model by conversation) or equivalent experience with the Modeling Assistant
- To run the result: Docker Desktop (or Docker Engine with Compose v2), or Python 3.11+ and Node.js 20+
- Optional: a GitHub account, for Push to GitHub and Continue from GitHub

Online version: https://labs.besser-pearl.org/labs/spec-driven-agent/

---

The Generate menu runs one deterministic generator over one diagram: the same model always gives the same files. The Spec-Driven Agent goes further. It starts from that deterministic scaffold, lets a language model fill the gaps your request asks for (a React frontend, extra pages, authentication, Docker files), and then validates the result and repairs what it can. You start it from the assistant chat, watch it work in a run card, and download a complete codebase.

In this lab you describe a small event-ticketing system, review the model, ask for the web app, and then run what comes out on your own machine. You also learn where the agent's limits are, because they decide how much you can trust the result.

> **Before you continue**
>
> The Spec-Driven Agent is marked experimental in the BESSER documentation. Its output is not reproducible: two runs on the same model give different code. Quality depends on the language model, and the free tier gives a thinner result than paid models. Fixes the agent makes during validation land in the generated code, not in your model, so a later from-scratch regeneration does not keep them, and neither does it keep hand edits. Treat the result as a starting point you review, not as a finished product.

### 1. Describe the system and review the model

The agent builds the application from the model, so the model has to be right first.

1. Open [https://editor.besser-pearl.org](https://editor.besser-pearl.org), click **Start describing** on the **Describe it** card, name the project `Event Ticketing` and click **Create Project**. (If you land on the canvas instead, use **File > New Project** and choose **Agentic**.)
2. Send this prompt:

```text
Create a class diagram for a small event ticketing system with the classes Venue, Event and Ticket. An event takes place at exactly one venue, a venue hosts many events, and an event has many tickets. Give each class a few attributes, including a price on Ticket.
```

3. When the reply arrives, click **Review the model**. The workspace closes and you see the class diagram on the canvas.
4. Check the model as in Lab 4: three classes, typed attributes, an association `Venue` 1 to many `Event`, and an association `Event` 1 to many `Ticket`. The assistant may draw `Event` to `Ticket` as a composition (a filled diamond), and the role names at the `Event` end can overlap; double-click an association to read its multiplicities. Fix anything wrong with a follow-up prompt or directly on the canvas.
5. Click **Quality Check** and resolve any errors. A valid model shows "Diagram is valid".

![The Event Ticketing class diagram: Event, Venue and Ticket with typed attributes, venue 1 to events 0..*, and event 1 to tickets 0..* drawn with a filled diamond](https://labs.besser-pearl.org/labs/spec-driven-agent/ticketing-class-diagram.png "Ticket has a price: float attribute. The two role names at the Event end overlap; drag a class to separate them")

Creating or editing a model never starts a generation run. The editor always waits for an explicit request.

> **If something goes wrong**
>
> **The assistant cannot build the model** (the reply says "I had a bit of trouble building everything at once..." and the classes only contain `id`). Use a template instead and continue with the next step: open **File > Load Template**, select **Class Diagram** on the left, pick **Library** and click **Load Template**. If the editor reports "Existing diagram detected", choose **Replace**. The Library template has three classes (`Library`, `Book`, `Author`), a `Genre` enumeration and an OCL constraint, which is a good size for a first run.
>
> ![The Load Template dialog with the Class Diagram category selected and the Library card checked](https://labs.besser-pearl.org/labs/spec-driven-agent/load-template-library.png "The Library class-diagram template is a small, valid model you can generate from")
>
> ![The Library template on the canvas: Book, Author, Library, the Genre enumeration and an OCL constraint on Book](https://labs.besser-pearl.org/labs/spec-driven-agent/library-model-canvas.png "Review the template model the same way: classes, attributes and the multiplicities on both associations")

> **Check your work**
>
> The **Class** editor shows a valid model of three connected classes (yours or the Library template), and Quality Check reports no errors.

### 2. Decide how the run is paid for and set a budget

A run uses a language model for the customisation and repair phases. There are two ways to pay for it.

- **No key (free tier).** If you have not saved an API key, the run uses the server-hosted free tier. No key dialog opens and no account is needed. The server picks the free model (the run card shows it, for example `free / moonshotai/Kimi-K3`), and it may switch to another free model during the run if the first one is unavailable. Quality is lower than with paid providers. It runs on shared hardware, so use it for real work, not for repeated test runs.
- **Your own key.** If you saved a key, the run is billed to that key as soon as you confirm it.

> **Before you continue**
>
> With a saved API key, clicking **Continue** after "generate the web app" starts a paid run. Set the run budget before you ask. The key is kept only in this browser tab's session storage, is never stored on the BESSER server, and is cleared when you close the tab.

1. Open the key dialog from the workspace: click **API key** in the bottom bar of the chat (or the **Change the model** link under the composer, or **Settings > AI / LLM API Key** in the sidebar). The dialog is titled **Use your own API key**.
2. Look at the **Provider** list. It contains **Free — included, no key required** next to Anthropic, OpenAI, Mistral and Nebius. The free option applies to the Spec-Driven Agent only.
3. Expand **Spec-Driven Agent settings**. It holds **Max spend / run (USD)** and **Max time / run (min)**. On the hosted editor both default to the server's ceiling, "Up to $5 and 40 min per run", and the server enforces those caps whatever you type.

![The Use your own API key dialog with the provider list, API Key and Model fields, and the expanded Spec-Driven Agent settings showing Max spend per run 5 and Max time per run 40](https://labs.besser-pearl.org/labs/spec-driven-agent/key-dialog-run-budget.png "The budget applies to runs billed to your key. A run that hits a cap stops and keeps what it produced")

4. For this lab, use the free tier: click **Cancel** without entering a key. If you do want to use your own key, enter it, lower **Max spend / run (USD)** (for example to 1), and click **Save**.

> **Note**
>
> If the server offers no free tier and you have no key, asking for a run opens a dialog titled **Spec-Driven Agent — Run** with a **Save & run** button instead. Dismissing it cancels the run.

> **Check your work**
>
> You know which way your run will be paid for. With no key saved, the bottom bar button still reads **API key** (it reads **API key set** once a key is saved).

### 3. Ask for the web app and watch the run card

1. Click **Describe your app** at the top of the canvas to reopen the chat.
2. Type the request exactly and press <kbd>Enter</kbd>:

```text
generate the web app
```

![The chat composer containing the text generate the web app](https://labs.besser-pearl.org/labs/spec-driven-agent/generate-web-app-prompt.png "Ask explicitly. A model on its own never starts a run")

Instead of typing, you can click a **Generate web app** or **Generate application** chip if the assistant offered one under its last reply. A request for an app, a web app, a UI or a dashboard always gets a frontend, even when the project has no GUI diagram.

3. The assistant does not start right away. It explains that BESSER generates the application with its built-in generators and uses a language model only for what they do not cover, mentions the free model and the **set up your own API key** link, and asks "Do you want to continue?". Click the **Continue** chip. If you do nothing, no run starts.

![The assistant's confirmation after generate the web app: an explanation of built-in generators and the free model, a set up your own API key link, Do you want to continue?, and a Continue chip](https://labs.besser-pearl.org/labs/spec-driven-agent/generate-web-app-continue.png "Nothing runs until you click Continue. The link opens the API key dialog from the previous step")

4. A run card titled **Spec-Driven Agent** appears a few seconds later, with the start of the run id, the provider and model (`free / ...` on the free tier) and a **Running** pill. While it runs it shows:
   - a phase list that ticks off in order: **Selecting generator**, **Running deterministic generator**, **Analysing gaps**, **Customising output**, **Validating**. The deterministic step names the BESSER generator it runs, for example `running generate_fastapi_backend`, and the customising step counts the model's actions;
   - extra rows when something changes, for example "Switched to poolside/laguna-s-2.1-free — The primary model was unavailable.";
   - a **Working…** strip (after about 45 seconds it adds "Big steps can take a few minutes — the timer keeps moving while it's running.");
   - streamed commentary from the model;
   - a footer with the elapsed time against the runtime cap (for example `5m 9s / 40m`) and a red **Stop** button.

![The run card at the Running deterministic generator phase: Selecting generator done, running generate_fastapi_backend with a spinner, the Working strip, 5m 9s / 40m and a red Stop button](https://labs.besser-pearl.org/labs/spec-driven-agent/run-card-deterministic.png "On the free tier, Selecting generator took about five minutes in our run; the deterministic generator itself then finished in seconds")

![The run card during Customising output: five phase rows including a model switch, 9 actions, the Working strip, the model's commentary about the backend contract and the React frontend, 12m 11s / 40m and Stop](https://labs.besser-pearl.org/labs/spec-driven-agent/run-card-customising.png "The commentary shows what the model is doing. The timer keeps moving while the run is alive")

5. Let it run. Free-tier runs are slow and the phase times vary a lot. In one of our runs **Selecting generator** alone took 5 minutes; in another the scaffold was generated within the first minute, **Customising output** started after 7 minutes, **Validating** after 21 minutes, and the run stopped at the 40-minute runtime cap. Plan for a run of 20 to 40 minutes. You can keep working in another tab. Reloading the page does not cancel the run: the editor reattaches to it and replays what you missed. It finds the run through this browser's storage, so stay in the same browser; a private window you close loses the card, and with it the download, even though the run keeps going on the server.
6. **Stop** ends the run (the button reads "Stopping…" while it winds down). The card then reports `CANCELLED`. Only one run can be live per tab; a second request gets "Spec-Driven Agent is already running — please wait for it to finish or click Stop."

> **If something goes wrong**
>
> **The assistant answers with a list of generators ("What would you like me to generate? Here are the available options...") and no run card appears.** The request was not routed to the Spec-Driven Agent; no run started and nothing was charged. Reply with the exact sentence `generate the web app` again, or click a **Generate application** chip under an earlier reply. If it keeps happening, the assistant service is degraded; try again later.
>
> **The progress stops updating.** If the stream is quiet for 60 seconds the editor says the run may still be finishing on the server and reconnects automatically, up to four times. Corporate networks and proxies that cut long-lived connections are a common cause; the run itself keeps going on the server.

> **Check your work**
>
> A run card is visible, its phases tick off one after another, and the **Working…** strip shows the elapsed time.

### 4. Read the finished run card

When the run ends, the card collapses to a short summary.

![The finished run card: Generated — incomplete, 12 unresolved blockers, generate_fastapi_backend, 15 files, the 20% files unchanged from scaffold badge, 383k tokens, Show steps, Download and Push to GitHub, a Verification line with 5 verified and 12 unverified, and two warnings about the runtime cap and unresolved issues](https://labs.besser-pearl.org/labs/spec-driven-agent/run-card-status.png "Our free-tier run hit the 40-minute cap. It still delivered a working app, but the card says plainly that it is not verified complete")

1. Read the status. **Application ready** means the run finished without unresolved blockers. Other outcomes are **Generated — incomplete** (with a count of unresolved blockers), **Delivered — rules not enforced** (a rule from your model was checked and found missing in the code), or an error code: `COST_CAP`, `TIMEOUT` or `INCOMPLETE` keep partial output; `UPSTREAM_LLM`, `INTERNAL` or `BAD_REQUEST` mean a provider or backend failure, so retry; `INVALID_KEY` clears your key. Our run ended as **Generated — incomplete** · 12 unresolved blockers, with the warnings "Runtime cap reached (2426.7s > 2400s). Output may be incomplete." and "The download is available for inspection and further work."
2. Next to the status you see the generator the run started from (`generate_fastapi_backend`) and the file count (15 files).
3. Click the badge that reads "N% files unchanged from scaffold". It opens **How this was built**: the share of scaffold files the run did not edit, the share BESSER generated and the model then edited, and the share of additional files outside the scaffold. Below that come the token counts and, on the free tier, "No cost — this run used the free tier." This is provenance, not a quality score. A high percentage means more of the app is deterministic BESSER output that follows your model exactly; the rest was written or edited by a language model and deserves a closer review.

![How this was built: 20% scaffold files not edited in this run, 47% generated by BESSER then edited in this run, 33% additional files outside the scaffold, 383k active tokens with 1.92M cached context, and No cost — this run used the free tier](https://labs.besser-pearl.org/labs/spec-driven-agent/run-card-how-built.png "Only 20% of the files are untouched BESSER output in this run, so most of the code needs a review")

4. Click **Show steps** to expand the phase timeline and the model's commentary again. **Hide steps** collapses it. Each phase row has a **details** link or an action count (here 56 actions while customising and 84 while validating) that you can open.

![The finished card with Show steps expanded: the five phase rows Selecting generator, Running deterministic generator, Analysing gaps, Customising output with 56 actions and Validating with 16 blockers / 38 total and 84 actions, followed by the model's plan](https://labs.besser-pearl.org/labs/spec-driven-agent/run-card-finished.png "The plan shows what the model decided on its own: here it added login and a ticket purchase endpoint, and built a static frontend served by FastAPI instead of a React app")

5. Read the verification line. It summarises the checks (in our run "5 verified · 12 unverified"); click it to see the individual findings. Unverified means unknown, not absent: the check could not run or did not pass, so you have to test that part yourself. In our run, the automatic check of `POST /auth/login` was refused because it sent an unknown user, while registering and logging in worked when we tried them by hand.

> **Note**
>
> Validation has a defined scope: syntax, imports, contracts and lint, plus sandboxed checks such as booting the backend or building the frontend where the server allows them. It does not prove every business requirement. Read the findings even when the card says **Application ready**.

> **Check your work**
>
> You can say which generator the run started from, how many files it produced, what percentage of files are unchanged from the scaffold, and how many checks are unverified.

### 5. Download the application and run it locally

1. Click **Download** on the card. Nothing is written to your machine until you click, and the archive stays on the server for about 30 minutes, so download it now.
2. Unzip the archive (named like `besser_smart_<run id>.zip`) into an empty folder.
3. Open `BESSER_GENERATION.md` at the top level. It records the BESSER version and build, the generator `spec_driven_agent`, the base generator (`generate_fastapi_backend` in our run) and the language model the run used. Keep it with the code.
4. Look at the layout before you run anything; it depends on the run. Our archive had no `README.md` and no `docker-compose.yml`, only a `backend/` folder with `main_api.py`, `requirements.txt`, the routers (`venue.py`, `event.py`, `ticket.py`, plus an added `auth.py`) and a `static/` folder with `index.html`, `app.js` and `styles.css`. Check which case you have:

**Case A: there is a `docker-compose.yml` at the top level.** With Docker running:

```bash
docker compose up --build
```

The web app is at http://localhost:3000, the API at http://localhost:8000, and the interactive API documentation at http://localhost:8000/docs. Stop it with <kbd>Ctrl+C</kbd>, then `docker compose down`.

**Case B: no compose file.** Start the backend from the folder that contains `main_api.py` and `requirements.txt`:

```bash
cd backend
python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
python main_api.py
```

```powershell
cd backend
python -m venv .venv
.venv\Scripts\Activate.ps1
pip install -r requirements.txt
python main_api.py
```

The backend listens on port 8000. If the backend has a `static/` folder (as in our run), it also serves the web app: open http://localhost:8000. If the archive instead has a separate frontend folder with a `package.json`, start it in a second terminal with `npm install` and `npm run dev`, and open http://localhost:3000.

5. Open the web app, create a venue, an event for it and a ticket, and check that the lists update. If the app asks you to log in, register an account first. Then open http://localhost:8000/docs and confirm there are endpoints for each class of your model.

![The generated Event Ticketing web app at localhost:8000, logged in as student, showing an upcoming event Spring Jazz Night at the venue Rockhal with Expected: 800, Tickets: 1, and Buy ticket, Edit and Delete buttons](https://labs.besser-pearl.org/labs/spec-driven-agent/running-app.png "Our run's app after registering, creating a venue and an event, and buying one ticket. The event was entered as 20:00 local time but is shown as 18:00: a time-zone bug in the generated frontend")

> **If something goes wrong**
>
> **Port 3000 or 8000 is already in use.** Stop the other process, or start the backend on another port and, for a separate frontend, point it at the backend with the `VITE_API_URL` environment variable, for example `VITE_API_URL=http://localhost:8080 npm run dev`. **The build fails.** Check the run card's findings first; a check listed as unverified may be exactly what fails. Fix the generated code by hand, or ask the agent to fix it within the retention window (next step).

> **Check your work**
>
> The application runs locally, you can create records through the UI, and http://localhost:8000/docs lists endpoints for the classes in your model.

### 6. Iterate on the generated app

While the previous run is still held on the server (about 30 minutes after it finished), a follow-up request edits that application instead of rebuilding it.

1. In the same project's chat, send:

```text
add a search page for events by name
```

2. The assistant asks you to confirm again before anything runs. For a change to an existing app the message reads "I'll update your existing app to make that change." and the chip is **Fix it**; otherwise it is the **Continue** message from before. Click the chip. The agent starts a new run in modify mode: it seeds the workspace with the previous output and changes it. This is a second run, with the same cost rules as the first (free tier, or billed to your key).
3. Download the new archive and compare it with the first one. Only the files related to the search page should have changed.

> **Before you continue**
>
> After the retention window the previous output is gone and a request like this produces a fresh build from the model. Edits you made by hand to the downloaded code are never carried into a new run. If you want to keep working on the same code later, push it to GitHub first (next step).

> **Check your work**
>
> A second run card appears, and its result contains your earlier application plus a search page for events.

### 7. Push to GitHub and continue from the repository

This step is optional and needs a GitHub account.

1. On a finished run card, click **Push to GitHub**. If you are not signed in, the editor first sends you through GitHub sign-in and reopens the dialog when you come back.
2. In the **Push to GitHub** dialog choose **Create new repo**, enter a **Repository Name** (for example `event-ticketing-app`), an optional **Description**, tick **Private repository** if you want, and click **Push to GitHub**. If the name already exists, the dialog tells you to push to it as an existing repository instead; **Use existing repo** pushes a later run into the same repository with **Push update**.

3. Open the repository on GitHub and check that it contains the application and `BESSER_GENERATION.md`.
4. Later, or on another computer, reopen it: choose **File > Import > From GitHub**, or click **Continue from GitHub** in the project hub (on the first-run screen, **More options** opens the hub).

![The project hub with four start cards: Create Blank, From Spreadsheet, Import Project and Continue from GitHub](https://labs.besser-pearl.org/labs/spec-driven-agent/project-hub-continue-github.png "Continue from GitHub reopens a repository that BESSER created")

5. Pick the repository and branch. The editor imports the model stored in the repository as a new project and links the repository, so your next request ("add a search page", "add an organiser to events") edits that application. A repository BESSER did not create is rejected with "This repo has no BESSER model — it wasn't created by BESSER, so there's nothing to continue from yet." Importing never overwrites the project you have open.

You can also ask in the chat: `continue from github.com/<owner>/<repo>`.

> **Check your work**
>
> The repository exists on GitHub, and after **Continue from GitHub** a new project shows the same class diagram as the one you generated from.

### 8. Exercise: change the model, not only the code

> **Exercise: Add a customer and regenerate**
>
> Add a `Customer` class to the ticketing model (a customer buys many tickets, each ticket belongs to at most one customer), validate it, and run "generate the web app" again. Compare the new download with your first one. Which files changed because the model changed, and which changed only because a language model wrote them differently this time?

<details>
<summary>Show a solution</summary>

Look at the files BESSER generates deterministically first (the ORM models, Pydantic classes and routers): their changes should all trace to `Customer` and the new association. Differences elsewhere, for example in LLM-written frontend pages, are the non-reproducible part. The "% files unchanged from scaffold" badge and **How this was built** help you tell the two apart.

</details>

> **Exercise: Generate menu versus Spec-Driven Agent**
>
> For the same model, use **Generate > Web > Full Backend** from the Class editor and compare that archive with the backend part of the Spec-Driven output. Write down two things the agent added and one reason you might prefer the deterministic output for a course project.

<details>
<summary>Show a solution</summary>

The deterministic backend is reproducible and follows the model exactly, which makes it easy to regenerate after a model change. The agent's version may add a frontend, extra endpoints or configuration that the templates do not produce, at the cost of review effort and reproducibility.

</details>

---

Checked against BESSER 8.0 on 2026-10-02.


<a id="lab-6"></a>

## Lab 6: From a class diagram to a database

A Library class diagram turned into SQL DDL for two dialects, a SQLite database created with SQLAlchemy, and a running FastAPI backend you fill through Swagger.

| Time | Level | Runs with | Do first | Track |
| --- | --- | --- | --- | --- |
| 50 min | Intermediate | Browser, Python | [Lab 1](https://labs.besser-pearl.org/labs/first-model/) | Data and databases |

**You'll learn to**

- Generate SQL DDL for SQLite and PostgreSQL from a class diagram and explain the differences
- Predict how classes, attributes, enumerations, associations and inheritance become tables, columns and keys
- Create a SQLite database from generated SQLAlchemy code and inspect its tables
- Run the generated FastAPI backend and create, read, update and delete records through Swagger

**You'll need**

- A modern browser
- Python 3.11 or 3.12 with pip
- A terminal and a folder you can unzip files into

**Files for this lab**

- [Finished Library DB project (JSON)](https://labs.besser-pearl.org/files/databases/library-db.json)
- [Table listing script (Python)](https://labs.besser-pearl.org/files/databases/list_tables.py)

Online version: https://labs.besser-pearl.org/labs/databases/

---

A class diagram already describes the data your application stores. In this lab you use the Web Modeling
Editor to turn the Library template into database code: plain SQL DDL for two dialects, SQLAlchemy models
that create a SQLite database, and a complete FastAPI backend with a REST API on top of it.

You read the real generated output at every step, so you learn the mapping rules by example: which UML
construct becomes a table, a column, a foreign key or a separate association table. Along the way you change
one association and add a subclass, and watch the schema change with them.

### 1. Load the Library template and check it

1. Open [editor.besser-pearl.org](https://editor.besser-pearl.org/) and create a new project with
   **File > New Project** (on a first visit, click **Start modelling** on the **Model it** card).
   Name it `Library DB` and click **Create Project**.
2. Open **File > Load Template**. In the dialog, **Class Diagram** is selected on the left and
   **Library** is preselected. Click **Load Template**.

![Load Template dialog with the Class Diagram category and the Library template selected](https://labs.besser-pearl.org/labs/databases/load-template-library.png "Class Diagram is the default category; Library is the first template")

3. Click **Quality Check** in the top bar (the check-mark icon). A message reports the OCL constraint
   `inv1` as valid and ends with "Diagram is valid".

![Library class diagram with Book, Author, Library, the Genre enumeration and an OCL constraint](https://labs.besser-pearl.org/labs/databases/library-template.png "Three classes, one enumeration, two associations and one OCL invariant")

Look at the model with a database designer's eye before you generate anything:

- `Book`, `Author` and `Library` are classes, so each becomes a table.
- `Genre` is an enumeration. `Book.genre` is typed with it.
- Book and Author are linked by an association with multiplicity `*` on the Book end and `1..*` on the Author end.
- Book and Library are linked by an association with `*` on the Book end and `1..*` on the Library end.
  Both ends allow many, so this is also many-to-many: a book can belong to several libraries.
- Both associations are named `books`.

> **Check your work**
>
> The canvas shows Book (six attributes and the `decrease_stock` method), Author, Library, the Genre
> enumeration with ten literals and the OCL note `context Book inv inv1: self.pages> 10`. Quality Check
> says the diagram is valid.

### 2. Generate SQL DDL for SQLite and PostgreSQL

1. Open **Generate > Database > SQL DDL**.

![Generate menu with the Database submenu open: SQL DDL, Supabase and SQLAlchemy DDL](https://labs.besser-pearl.org/labs/databases/generate-menu-database.png "The Database submenu has three generators")

2. In the **SQL Dialect Selection** dialog, keep **Dialect** on **SQLite** and click **Generate**.
   The browser downloads `tables.sql`. Rename it to `tables_sqlite.sql`.
3. Open **Generate > Database > SQL DDL** again, choose **PostgreSQL** and click **Generate**.
   Rename this download to `tables_postgresql.sql`.

![SQL Dialect Selection dialog with the dialect list open](https://labs.besser-pearl.org/labs/databases/sql-dialect-options.png "Six dialects: SQLite, PostgreSQL, MySQL, MS SQL Server, MariaDB and Oracle")

> **Note**
>
> The dialog remembers the dialect you used last. Check the **Dialect** field every time you generate.

Open both files side by side. This is the `book` table and the two association tables from the SQLite file:

```sql
CREATE TABLE book (
	id INTEGER NOT NULL, 
	title VARCHAR(100) NOT NULL, 
	pages INTEGER NOT NULL, 
	stock INTEGER NOT NULL, 
	price FLOAT NOT NULL, 
	release DATE NOT NULL, 
	genre VARCHAR(10) NOT NULL, 
	PRIMARY KEY (id)
)

CREATE TABLE books (
	books INTEGER NOT NULL, 
	library INTEGER NOT NULL, 
	PRIMARY KEY (books, library), 
	FOREIGN KEY(books) REFERENCES book (id), 
	FOREIGN KEY(library) REFERENCES library (id)
)

CREATE TABLE books_1 (
	authors INTEGER NOT NULL, 
	books INTEGER NOT NULL, 
	PRIMARY KEY (authors, books), 
	FOREIGN KEY(authors) REFERENCES author (id), 
	FOREIGN KEY(books) REFERENCES book (id)
)
```

And the same `book` table in the PostgreSQL file:

```sql
CREATE TYPE genre AS ENUM ('Poetry', 'Thriller', 'History', 'Technology', 'Romance', 'Horror', 'Adventure', 'Philosophy', 'Cookbooks', 'Fantasy');

CREATE TABLE book (
	id SERIAL NOT NULL, 
	title VARCHAR(100) NOT NULL, 
	pages INTEGER NOT NULL, 
	stock INTEGER NOT NULL, 
	price FLOAT NOT NULL, 
	release DATE NOT NULL, 
	genre genre NOT NULL, 
	PRIMARY KEY (id)
)
```

What the two files tell you:

| UML construct | Becomes | Dialect difference |
|---|---|---|
| Class `Book` | Table `book` with a surrogate key `id` | SQLite `INTEGER`, PostgreSQL `SERIAL` (auto-increment) |
| Attribute `title: str` | Column `VARCHAR(100) NOT NULL` | none |
| Enumeration `Genre` | Values of `book.genre` | SQLite stores a `VARCHAR(10)` (the longest literal); PostgreSQL creates a real `genre` type |
| Many-to-many association | A separate table, named after the association, with a composite primary key of two foreign keys | none |

Because both associations are called `books`, the second table is renamed `books_1`. The columns are named
after the association ends (`authors`, `books`, `library`), so role names matter in the schema.

> **Check your work**
>
> You have `tables_sqlite.sql` and `tables_postgresql.sql`. Both contain the tables `author`, `book`,
> `library`, `books` and `books_1`. Only the PostgreSQL file starts with `CREATE TYPE genre AS ENUM` and uses
> `SERIAL` and a `genre` column of type `genre`.

### 3. Turn one association into a foreign key and add a subclass

Many-to-many is not the usual design for libraries and books. Make each book belong to exactly one library,
and add an `EBook` subclass so you can see how inheritance is stored.

1. Double-click the association line between Book and Library. The properties panel opens on the right.
2. Under **Library**, change **Multiplicity** from `1..*` to `1`. Leave the Book end at `*`.

![Association properties with the Library multiplicity set to 1 and the Book multiplicity set to *](https://labs.besser-pearl.org/labs/databases/association-library-multiplicity.png "One library has many books; each book has exactly one library")

3. Drag the first **Class** element from the palette onto the empty area below Book. Double-click it,
   rename it to `EBook`, and rename its attribute to `file_format` (type `str`).
4. Click EBook, then drag from one of the blue connection points on its top edge to the bottom edge of Book.
5. Double-click the new line. In the properties panel, open the dropdown that reads **Association** and
   choose **Generalization**.

![Relationship type dropdown with Association, Composition and Generalization](https://labs.besser-pearl.org/labs/databases/relationship-type-generalization.png "Draw the line from the subclass to the superclass, then switch its type")

6. Click **Quality Check** again.

![Extended diagram: EBook inherits from Book and the Library end of its association shows 1](https://labs.besser-pearl.org/labs/databases/library-extended.png "The hollow triangle points at the superclass Book")

7. Generate the SQL DDL again for SQLite and for PostgreSQL, as in the previous step.

The new SQLite `book` and `ebook` tables:

```sql
CREATE TABLE book (
	id INTEGER NOT NULL, 
	title VARCHAR(100) NOT NULL, 
	pages INTEGER NOT NULL, 
	stock INTEGER NOT NULL, 
	price FLOAT NOT NULL, 
	release DATE NOT NULL, 
	genre VARCHAR(10) NOT NULL, 
	library_id INTEGER NOT NULL, 
	type_spec VARCHAR(50) NOT NULL, 
	PRIMARY KEY (id), 
	FOREIGN KEY(library_id) REFERENCES library (id)
)

CREATE TABLE ebook (
	id INTEGER NOT NULL, 
	file_format VARCHAR(100) NOT NULL, 
	PRIMARY KEY (id), 
	FOREIGN KEY(id) REFERENCES book (id)
)
```

Two mapping rules are visible here:

- **One-to-many becomes a foreign key.** The `books` association table is gone. The "many" side, `book`,
  gets a column `library_id` that references `library (id)`. It is `NOT NULL` because the multiplicity is
  exactly `1`. The Book and Author association is still many-to-many, so `books_1` stays.
- **Inheritance becomes joined tables.** `ebook` holds only the attribute EBook adds, and its `id` is both
  its primary key and a foreign key to `book.id`. The parent table gets a `type_spec` column that records
  which class each row belongs to. Reading an e-book joins the two tables.

> **Check your work**
>
> The new DDL has five tables: `author`, `library`, `book` (with `library_id` and `type_spec`), `books_1`
> and `ebook`. There is no table called `books` any more.

### 4. Create a SQLite database with SQLAlchemy

The SQL file is text. SQLAlchemy code is Python that can create the database for you and is the same layer
the generated backend uses.

1. Open **Generate > Database > SQLAlchemy DDL**. In **SQLAlchemy DBMS Selection**, make sure
   **DBMS** is **SQLite** and click **Generate**. The browser downloads `sql_alchemy.py`.

![SQLAlchemy DBMS Selection dialog with SQLite selected](https://labs.besser-pearl.org/labs/databases/sqlalchemy-dbms-dialog.png "The same six database systems as the SQL DDL generator")

2. Create a working folder, move `sql_alchemy.py`, `tables_sqlite.sql` and
   [list_tables.py](https://labs.besser-pearl.org/files/databases/list_tables.py) into it, and install SQLAlchemy:

```bash
python -m pip install "sqlalchemy>=2.0"
```

3. Run the generated file. It creates a `data` folder and the database `data/Library.db`:

```bash
python sql_alchemy.py
```

4. List the tables and their columns with the provided script, which uses only Python's built-in `sqlite3` module:

```python
import sqlite3

con = sqlite3.connect("data/Library.db")
for (name,) in con.execute("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name"):
    cols = [row[1] for row in con.execute(f"PRAGMA table_info({name})")]
    print(f"{name}: {', '.join(cols)}")
```

```bash
python list_tables.py
```

```text
author: id, name, birth
book: id, title, pages, stock, price, release, genre, library_id, type_spec
books_1: authors, books
ebook: id, file_format
library: id, name, web_page, address, telephone
```

Open `sql_alchemy.py` and find the same rules in Python form: `class Genre(enum.Enum)`, a `Table_("books_1", ...)`
for the many-to-many association, `library_id ... ForeignKey_("library.id")` on `Book`, and
`class EBook(Book)` with `"polymorphic_on": "type_spec"`. The connection string is read from the
`DATABASE_URL` environment variable and falls back to `sqlite:///./data/Library.db`.

5. Optional: run the SQL file directly. Save this as `run_ddl.py` and run it:

```python
import sqlite3

con = sqlite3.connect("ddl_test.db")
con.executescript(open("tables_sqlite.sql", encoding="utf-8").read())
print([name for (name,) in con.execute("SELECT name FROM sqlite_master WHERE type='table'")])
```

```text
['author', 'library', 'book', 'books_1', 'ebook']
```

> **Note**
>
> Near the top of `Library`, `sql_alchemy.py` contains a comment saying the code of `cheapest_book_by` does
> not compile. That method is written in the BESSER Action Language, and this standalone file only keeps
> Python method bodies. The backend you generate next turns the same method into a working REST endpoint.

> **If something goes wrong**
>
> `ModuleNotFoundError: No module named 'sqlalchemy'` means the `pip install` went to a different Python than
> the one running the script. Use `python -m pip install ...` with exactly the same `python` command you use
> to run the file, or create a virtual environment as in the next step.

> **Check your work**
>
> `data/Library.db` exists and `list_tables.py` prints the five tables above.

### 5. Generate the Full Backend and run it

The Full Backend generator adds Pydantic schemas, routers and a FastAPI application on top of the same
SQLAlchemy models.

1. Open **Generate > Web > Full Backend**. There is no dialog: the browser downloads `backend_output.zip`.

![Generate menu with the Web submenu open: Django Project, Spring Project, Full Backend and Web Application](https://labs.besser-pearl.org/labs/databases/generate-menu-full-backend.png "Full Backend downloads immediately")

2. The zip has no top-level folder, so create one first and extract into it, for example `library_backend/`.
   You get `main_api.py`, `database.py`, `sql_alchemy.py`, `pydantic_classes.py`, `bal_stdlib.py`,
   `requirements.txt` and a `routers/` folder with one router per class plus `book_methods.py` and
   `library_methods.py`.
3. Create a virtual environment, install the requirements and start the server from inside that folder:

```bash
cd library_backend
python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
uvicorn main_api:app --reload
```

```powershell
cd library_backend
python -m venv .venv
.venv\Scripts\Activate.ps1
pip install -r requirements.txt
uvicorn main_api:app --reload
```

The server prints `Uvicorn running on http://127.0.0.1:8000`. On startup it creates `data/Library.db`
inside `library_backend/`, separate from the database of the previous step.

> **If something goes wrong**
>
> If PowerShell refuses to run `Activate.ps1`, run `Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass`
> in the same window and activate again. If port 8000 is taken, start with `uvicorn main_api:app --reload --port 8001`
> and use that port in the URLs below.

4. Open [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs).

![Swagger UI titled Library API with the System and Library endpoint groups](https://labs.besser-pearl.org/labs/databases/swagger-overview.png "Each class gets list, create, count, paginated, search, get, update, delete and bulk endpoints")

> **Check your work**
>
> Swagger shows "Library API" with groups for System, Library, Book, EBook and Author, plus
> "Relationships" and "Methods" groups. `GET /health` returns `"status": "healthy"`.

### 6. Create, read, update and delete records through Swagger

The order matters because of the multiplicities: a Book needs exactly one Library and at least one Author,
so create those first.

1. Expand **POST /library/**, click **Try it out**, replace the example body with the following and click **Execute**:

```json
{
  "name": "City Library",
  "address": "1 Main Street",
  "telephone": "+352 123 456",
  "web_page": "https://library.example.org"
}
```

![Request body for POST /library/ in Swagger](https://labs.besser-pearl.org/labs/databases/swagger-post-library-request.png "Only the attributes are required; the books list is optional")

The response is `200` with `"id": 1` and `"books_ids": []`.

2. Create an author with **POST /author/**:

```json
{
  "name": "Ada Writer",
  "birth": "1970-05-01"
}
```

3. Try to create a book that breaks the OCL invariant. Use **POST /book/** with `"pages": 5`:

```json
{
  "title": "Tiny",
  "pages": 5,
  "stock": 1,
  "price": 2.5,
  "release": "2024-03-15",
  "genre": "Poetry",
  "library": 1,
  "authors": [1]
}
```

![422 response with the message Value error, pages must be > 10](https://labs.besser-pearl.org/labs/databases/swagger-post-book-ocl-error.png "The OCL constraint inv1 became a Pydantic validator")

4. Execute **POST /book/** again with a valid book. `library` is the foreign key you saw in the DDL,
   `authors` fills the `books_1` association table, and `genre` must be one of the enumeration literals:

```json
{
  "title": "Modeling 101",
  "pages": 240,
  "stock": 5,
  "price": 29.9,
  "release": "2024-03-15",
  "genre": "Technology",
  "library": 1,
  "authors": [1]
}
```

The response contains `"library_id": 1`, `"type_spec": "book"` and `"author_ids": [1]`.

5. Read the relationship back with **GET /library/{library_id}/books/** and `library_id` = `1`.

![Response of GET /library/1/books/ listing one book with library_id 1](https://labs.besser-pearl.org/labs/databases/swagger-get-library-books.png "The one-to-many association has its own read endpoint")

6. Update: use **PUT /book/{book_id}/** with `book_id` = `1` and the same body as in step 4 but `"stock": 4`.
7. Call a modeled method: **POST /book/{book_id}/methods/decrease_stock/** with `book_id` = `1` and the body
   `{"params": {"qty": 1}}`. The response reports `"status": "executed"`, and a new `GET /book/1/` shows `"stock": 3`.
8. Delete: create an e-book with **POST /ebook/** (the valid book body plus `"file_format": "EPUB"`), then
   remove it with **DELETE /ebook/{ebook_id}/**. Before you delete it, run **GET /book/**: the e-book is
   listed among the books with `"type_spec": "ebook"`, because its common columns live in the `book` table.

> **Note**
>
> Object diagrams do not fill the database. The Web Application and Full Backend generators ignore them, and
> **Generate > Data > JSON Object Export** only writes a JSON file. Seed data goes in through the API, as you
> did here, or through your own script.

> **Check your work**
>
> `GET /book/` returns one book with `"stock": 3`, the 422 error shows that the OCL constraint is enforced, and
> `GET /book/count/` returns `{"count": 1}` after you deleted the e-book.

### 7. Exercise: extend the model with loans

> **Exercise: Model book loans**
>
> Add a `Member` class (`name`, `email`) and a `Loan` class (`start: date`, `due: date`, `returned: bool`).
> A member has many loans, each loan is for exactly one book, and a book can be on many loans over time.
> Before you generate anything, write down the tables and foreign keys you expect. Then generate the
> PostgreSQL DDL and compare it with your prediction. Finally regenerate the Full Backend and create a member,
> a loan and a book through Swagger.

<details>
<summary>Show a solution</summary>

Two one-to-many associations (Member 1 to Loan `*`, Book 1 to Loan `*`) give `loan` two `NOT NULL` foreign
key columns and no association table. If you made either end `0..1` instead of `1`, check how that changes
the `NOT NULL` on the foreign key.

</details>

> **Exercise: Change the inheritance**
>
> Make `Book` abstract and add a second subclass `PrintedBook` with `weight_g: int`. Regenerate the SQL DDL.
> Does `book` still get its own table, and does `type_spec` still appear? Read the warning about inheritance
> in the [SQLAlchemy generator documentation](https://besser.readthedocs.io/en/latest/generators/alchemy.html)
> to explain what you see.

<details>
<summary>Show a solution</summary>

Joined-table inheritance is the default. The documentation describes when the generator switches to a
different strategy for abstract parents, and the condition depends on whether the parent has relationships.
Book has two, so compare your output with that rule.

</details>

---

Checked against BESSER 8.0 on 2026-10-02.


<a id="lab-7"></a>

## Lab 7: Build a full web app from three models

A Library web application with tables, a bar chart and a chatbot, generated from a class diagram, a GUI model and an agent model, and running locally with Docker Compose.

| Time | Level | Runs with | Do first | Track |
| --- | --- | --- | --- | --- |
| 1 h 15 min | Intermediate | Browser, Docker | [Lab 1](https://labs.besser-pearl.org/labs/first-model/) | Full applications |

**You'll learn to**

- Combine a class diagram, an agent diagram and a GUI model in one project
- Generate a GUI from a class diagram and extend it with a chart and a chatbot widget
- Generate the full web application and run it with Docker Compose
- Fill the database through the generated REST API and see the data in the frontend

**You'll need**

- A modern browser
- Docker Desktop (or Docker Engine with the Compose plugin), running
- About 5 GB of free disk space for the three images
- A tool to unzip files

**Files for this lab**

- [Finished Library App project (JSON)](https://labs.besser-pearl.org/files/web-app/library-app.json)

Online version: https://labs.besser-pearl.org/labs/web-app/

---

A web application needs at least three things: the data it manages, the screens people use, and often an
assistant that answers questions. In BESSER each of these is a separate model in the same project: a class
diagram, a GUI model and an agent diagram. The Web Application generator reads all three and produces a
FastAPI backend, a React frontend, one service per agent and a `docker-compose.yml` that starts everything.

In this lab you build a small Library application. You reuse two templates so the result is predictable,
design the screens in the no-code GUI editor, generate the code, run it with Docker and fill it with data.

### 1. Create a Full Web Application project

1. Open [editor.besser-pearl.org](https://editor.besser-pearl.org/) and open **File > New Project**
   (on a first visit, click **Start modelling** on the **Model it** card).
2. Name the project `Library App`, keep **Low-code**, and choose the modeling perspective
   **Full Web Application**. Click **Create Project**.

![Create A Project form with the name Library App, the Low-code view and the Full Web Application perspective](https://labs.besser-pearl.org/labs/web-app/new-project-full-web-app.png "The Full Web Application perspective shows exactly the three diagram types this lab needs")

3. Load the data model: **File > Load Template**, category **Class Diagram**, template **Library**,
   then **Load Template**. Click **Quality Check**; it reports "Diagram is valid".

> **Check your work**
>
> The sidebar lists **Class**, **Agent** and **GUI**. The Class editor shows Book, Author, Library and
> the Genre enumeration.

### 2. Add the Greeting Agent

1. Click **Agent** in the sidebar.
2. Open **File > Load Template**, choose the category **Agent Diagram** and the template
   **Greeting Agent**, then click **Load Template**.
3. Click **Quality Check**. It reports "Diagram is valid".

![Greeting Agent state machine: initial, greeting, good and bad states connected by intents and Auto transitions](https://labs.besser-pearl.org/labs/web-app/greeting-agent.png "Each state has fixed text replies; intents decide which transition fires")

Read the model before you continue. The agent waits in `initial`. When the user's message matches
`greeting_intent` (training sentences such as "Hi", "Hello", "Howdy") it moves to `greeting`, which replies
"Hi" and "How are you?". The answer is classified as `good_intent` or `bad_intent`, the matching state
replies, and an **Auto** transition returns to `initial`. No language model is involved, so the agent needs
no API key.

> **Check your work**
>
> The Agent editor shows four states (`initial`, `greeting`, `good`, `bad`), three intent transitions and two
> **Auto** transitions back to `initial`.

### 3. Generate the GUI from the class diagram

1. Click **GUI** in the sidebar. The page builder opens with an empty canvas. The **REFERENCES** bar shows
   that this GUI uses the class diagram `Library`.

![Empty GUI editor with the device icons and the magic-wand button on the left of the toolbar](https://labs.besser-pearl.org/labs/web-app/gui-editor-empty.png "The magic wand next to the desktop, tablet and phone icons generates a GUI")

2. Click the magic-wand button, **Auto-Generate GUI from Class Diagram**.
3. The dialog warns that it will clear the current GUI and lists what it creates. Click **Generate GUI**.

![Auto-Generate GUI from Class Diagram dialog listing a navigation panel, a page per class and method buttons](https://labs.besser-pearl.org/labs/web-app/auto-generate-gui-dialog.png "Auto-generation replaces the whole GUI, so run it before you customise anything")

4. Open the **Pages** panel (the right-most icon in the panel toolbar) and click the **Book** page.

![Generated Book page with a navigation sidebar, the Book List table, an Add Book button and a decrease_stock button](https://labs.besser-pearl.org/labs/web-app/gui-autogenerated-book-page.png "One page per class, each with a data table bound to that class and buttons for its methods")

> **Before you continue**
>
> **Auto-Generate GUI from Class Diagram** cannot be undone and removes everything you added by hand,
> including chatbot widgets. Run it first, then customise.

> **Check your work**
>
> The **Pages** panel lists Book (`/book`), Library (`/library`) and Author (`/author`). The Book page shows a
> table with the columns Title, Pages, Stock, Price, Release, Genre, Library and Authors.

### 4. Add a bar chart and the chatbot widget

The table already exists. Add a chart of book prices and the Greeting Agent as a chat window on the Book page.

1. Open the **Open Blocks** panel (the plus icon in the panel toolbar). Drag **Bar Chart** from the
   **Basic** group onto the Book page, below the **decrease_stock** button.
2. Click the chart to select it. The **Component settings** panel opens. Set:
   - **Chart Title**: `Book prices`
   - Under **Chart Series** > **Series 1**: **Data Source** `Book`, **Label Field** `title`, **Data Field** `price`

![Bar chart selected on the Book page with Chart Title Book prices and a series bound to Book, title and price](https://labs.besser-pearl.org/labs/web-app/gui-bar-chart-settings.png "The preview shows sample bars; the generated app plots the real records")

3. Open **Open Blocks** again and drag **BESSER Agent** onto the Book page, above the Book List table.
4. Click the widget. In **Component settings**, choose `Greeting Agent` in the **Agent** field and set
   **Agent Title** to `Library assistant`.

![BESSER Agent widget titled Library assistant with Greeting Agent chosen in the Agent field](https://labs.besser-pearl.org/labs/web-app/gui-agent-widget-settings.png "Choose the agent explicitly; the widget stores its name and the generated app connects to that agent")

> **Note**
>
> The editor saves the GUI automatically; the status at the bottom right changes to "Saved". Charts and tables
> show placeholder data in the editor because the database does not exist yet.

> **If something goes wrong**
>
> If a block does not land on the page, drop it onto an existing element such as the table or the button: the
> blue outline shows where it will be inserted. Use the arrow and move icons on the selected element's toolbar
> to change its position afterwards.

> **Check your work**
>
> The Book page contains, from top to bottom, the Library assistant chat window, the Book List table, the
> **decrease_stock** button and the Book prices chart.

### 5. Generate the web application

1. With the GUI editor open, choose **Generate > Web Application**. (From the class diagram, the same
   generator is under **Generate > Web > Web Application**.)
2. The **Web Application Generator** dialog lists the diagrams it will use. Check that both required
   diagrams have a green tick, then click **Generate**.

![Web Application Generator dialog with the Library class diagram and the GUI diagram ticked and one agent diagram available](https://labs.besser-pearl.org/labs/web-app/web-app-generator-dialog.png "Agent diagrams are optional and are included through the widgets that reference them")

3. The browser downloads `web_app_output.zip`. The zip has no top-level folder, so create a folder
   `library_app/` and extract it there. You get:

```text
library_app/
├── docker-compose.yml
├── BESSER_GENERATION.md
├── backend/          FastAPI app: main_api.py, routers/, sql_alchemy.py, pydantic_classes.py, Dockerfile
├── frontend/         React + TypeScript (Vite): src/pages/Book.tsx, Library.tsx, Author.tsx, Dockerfile
└── agents/
    └── greeting_agent/   Greeting_Agent.py, config.yaml, Dockerfile
```

Open `frontend/src/pages/Book.tsx`. Your GUI model is now code: you find
`<AgentComponent ... agent-name="Greeting Agent" agent-title="Library assistant" />` and a
`<ChartBlock ... chartType="bar-chart" title="Book prices" ...>`.

> **If something goes wrong**
>
> "Cannot generate web application: GUI diagram is empty." means the GUI model has no pages. The dialog warns
> about it with "(empty - will be skipped)". Go back to the GUI editor and run
> **Auto-Generate GUI from Class Diagram** first.

> **Check your work**
>
> `library_app/` contains `docker-compose.yml` and the folders `backend`, `frontend` and `agents/greeting_agent`.

### 6. Run the application with Docker Compose

`docker-compose.yml` defines three services: `frontend` on port 3000, `backend` on port 8000 with a SQLite
database in the volume `sqlite_data`, and `greeting_agent_agent` with its WebSocket on port 8765 (and 5000).

1. Make sure ports 3000, 8000, 8765 and 5000 are free, then start everything from `library_app/`:

```bash
docker compose up --build
```

The first build downloads Python, Node and PyTorch layers and takes several minutes (about 7 minutes on a
fast connection; the agent image alone is about 3 GB). It is ready when the log shows these three lines:

```text
backend-1               | INFO:     Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
greeting_agent_agent-1  | ... Greeting_Agent's WebSocketPlatform starting at ws://0.0.0.0:8765
frontend-1              |  INFO  Accepting connections at http://localhost:3000
```

The agent also logs an error about the monitoring database (`could not translate host name "YOUR-DB-HOST"`).
Monitoring is optional and the agent works without it.

2. Open [http://localhost:3000](http://localhost:3000). The app opens on the Book page. The table and the
   chart are empty because the database is empty.
3. Type `Hello` in the chat window and press <kbd>Enter</kbd>, then answer `Fine`.

![Running app with the Library assistant chat: Hello, Hi, How are you?, Fine, I am glad to hear that!](https://labs.besser-pearl.org/labs/web-app/app-agent-chat.png "The status turns to Connected when the frontend reaches the agent's WebSocket")

> **If something goes wrong**
>
> If `pip install` or `npm install` fails during the build with `CERTIFICATE_VERIFY_FAILED` or
> `self-signed certificate in certificate chain`, your network inspects HTTPS traffic and the containers do
> not trust its certificate. Build on another network, or ask your IT department how to add their certificate
> to Docker builds. If a port is already in use, stop the other program or change the left-hand port numbers
> in `docker-compose.yml`.

> **Check your work**
>
> `docker compose ps` lists three running services, http://localhost:3000 shows the Book page, and the chat
> header says "Connected".

### 7. Fill the database through Swagger and see it in the app

The backend is the same kind of FastAPI service you would get from **Generate > Web > Full Backend**, with
interactive documentation at [http://localhost:8000/docs](http://localhost:8000/docs).

1. In Swagger, expand **POST /library/**, click **Try it out**, and execute:

```json
{
  "name": "City Library",
  "address": "1 Main Street",
  "telephone": "+352 123 456",
  "web_page": "https://library.example.org"
}
```

2. Create an author with **POST /author/**:

```json
{
  "name": "Ada Writer",
  "birth": "1970-05-01"
}
```

3. Create three books with **POST /book/**, changing `title`, `price` and `genre` each time. In the
   Library template a book can belong to several libraries, so `library` is a list here:

```json
{
  "title": "Modeling 101",
  "pages": 240,
  "stock": 5,
  "price": 29.9,
  "release": "2024-03-15",
  "genre": "Technology",
  "library": [1],
  "authors": [1]
}
```

The other two books used in the screenshot are `Patterns in Practice` (42.5, Technology) and
`Night Train` (12.0, Thriller). Remember that the OCL constraint requires more than 10 pages.

4. Reload http://localhost:3000. The Book List shows the three books with their library and author, and the
   Book prices chart draws one bar per book.

![Running app: Book List with three books and the Book prices bar chart](https://labs.besser-pearl.org/labs/web-app/app-book-table-chart.png "Table rows and chart bars come from GET requests to the backend")

5. Try the generated frontend as a user: open the Author page, click **Add Author**, fill in Name and Birth
   and submit. The form also offers the existing books as relationships. The pencil and bin icons in each row
   edit and delete records without Swagger.

When you are done, press <kbd>Ctrl+C</kbd> in the terminal and run `docker compose down`. Add `-v`
(`docker compose down -v`) only if you also want to delete the database volume.

> **Check your work**
>
> The Book page lists three books, the chart has three bars, and the Library page shows City Library with
> its books.

### 8. Exercise: a digital twin dashboard

> **Exercise: Model and run a digital twin application**
>
> Build a new project for a digital twin. Model `PhysicalThing` (`name`, `location`), `DigitalTwin` (`status`,
> `lastSync`), `Sensor` (`type`, `unit`) and `Measurement` (`timestamp`, `value: float`). A physical thing has
> zero or more sensors and digital twins; a sensor produces many measurements. Auto-generate the GUI, then add
> a line chart of measurement values over time on the Measurement page. Generate the application, run it, and
> fill it through Swagger in the right order so every mandatory association end has a target.

<details>
<summary>Show a solution</summary>

Decide the multiplicities first: `1` on the PhysicalThing end and `0..*` on the Sensor end means every
sensor needs an existing physical thing when you create it. For the line chart, use `timestamp` as the label
field and `value` as the data field.

</details>

> **Exercise: Replace the Greeting Agent with your own assistant**
>
> Create an agent with an initial state and at least six states that each reply with a fixed text: what a
> digital twin is, how sensors work, how to read a measurement, help, back and exit. Give the states a
> fallback body that answers messages matching no intent. Put the agent on the dashboard page with the
> **BESSER Agent** block and regenerate.

<details>
<summary>Show a solution</summary>

Start from the Greeting Agent structure: one hub state that every answer state returns to with an
**Auto** transition. Intent names must differ from state names, so use names like `sensor_intent`.

</details>

---

Checked against BESSER 8.0 on 2026-10-02.


<a id="lab-8"></a>

## Lab 8: Publish your app to Render, then extend it

Your Library web app published from the editor to a new GitHub repository, deployed on Render's free tier, then extended with a Publisher concept and redeployed.

| Time | Level | Runs with | Do first | Track |
| --- | --- | --- | --- | --- |
| 45 min | Intermediate | Browser, GitHub | [Lab 7](https://labs.besser-pearl.org/labs/web-app/) | Full applications |

**You'll learn to**

- Connect the editor to GitHub and publish a project as a new repository
- Explain what the generated repository and its Render Blueprint contain
- Deploy the backend, frontend and agent services on Render's free tier
- Change the models, update the same repository and redeploy

**You'll need**

- The Library App project from the web-app lab (or its JSON export)
- A GitHub account
- A free Render account (you can sign up with GitHub)

**Files for this lab**

- [Starting project: Library App (JSON)](https://labs.besser-pearl.org/files/deploy-render/library-app.json)

Online version: https://labs.besser-pearl.org/labs/deploy-render/

---

In the [web-app lab](https://labs.besser-pearl.org/labs/web-app/) you ran the generated application on your own machine. Here you put
the same application on the internet. The editor generates the code, pushes it to a new repository in your
GitHub account together with a `render.yaml` Blueprint, and Render builds and hosts the three services that
Blueprint describes.

Then you do what real projects do next: change the requirements. You add publishers to the domain model,
teach the agent a new question, update the GUI and publish again to the same repository.

> **Before you continue**
>
> This lab creates a repository in your GitHub account (public by default) and three services in your Render
> account. The services use Render's free plan, which costs nothing but sleeps after 15 minutes without
> traffic. Delete the Blueprint on Render and the repository on GitHub when you no longer need them.

### 1. Open the project and check the models

1. Open [editor.besser-pearl.org](https://editor.besser-pearl.org/) in the same browser you used for the
   web-app lab. Projects live in the browser's storage, so `Library App` is still there: open it with
   **File > Open Project**.
   If you use a different browser, download the [starting project](https://labs.besser-pearl.org/files/deploy-render/library-app.json) and open it
   with **File > Import > Project file (.json / .py)**.
2. Run **Quality Check** on the **Class** and on the **Agent** diagram. Both report "Diagram is valid".
3. Open the **GUI** editor and check that the Book page still has the Library assistant widget with
   `Greeting Agent` selected in its **Agent** field.

> **Note**
>
> Publishing needs a class diagram and a GUI model (for a web app) or an agent diagram (for a standalone
> agent). **Deploy > Publish to Render** is only enabled while a Class, GUI or Agent diagram is open.

> **Check your work**
>
> The project has a valid Library class diagram, a valid Greeting Agent, and a GUI whose Book page contains the
> table, the chart and the chat widget.

### 2. Connect GitHub

1. Open the **Deploy** menu. While you are not signed in, it shows two items.

![Deploy menu with the Deployment header, Connect GitHub to Deploy and Publish to Render](https://labs.besser-pearl.org/labs/deploy-render/deploy-menu-signed-out.png "Connect GitHub to Deploy disappears once you are signed in")

If you click **Publish to Render** now, the editor only shows a reminder:

![Information toast: Connect to GitHub first.](https://labs.besser-pearl.org/labs/deploy-render/toast-connect-github-first.png "Publishing always starts with a GitHub sign-in")

2. Click **Deploy > Connect GitHub to Deploy** (or the GitHub icon in the top bar). The editor redirects you
   to GitHub.

![GitHub sign-in page asking you to continue to BESSER Web Modeling Editor](https://labs.besser-pearl.org/labs/deploy-render/github-sign-in.png "Check that the page names BESSER Web Modeling Editor before you sign in")

3. Sign in and authorize the application. It asks for the `repo`, `gist` and `user` scopes, because it creates
   repositories and pushes code on your behalf.
4. Back in the editor, a toast says "Signed in as" followed by your GitHub user name.

> **If something goes wrong**
>
> If you return to the editor and still see **Connect GitHub to Deploy**, the sign-in did not complete. Try
> again in a normal (not private) window and allow pop-ups and redirects for editor.besser-pearl.org. The
> session lasts 24 hours; after that, sign in again.

> **Check your work**
>
> The **Deploy** menu now shows only **Publish to Render**, and the top bar shows your GitHub account.

### 3. Publish the project to a new repository

1. With the **Class** or **GUI** diagram open, choose **Deploy > Publish to Render**. The
   **Publish to Render** dialog opens with the text "Create a GitHub repository from the current project and
   deploy it on Render."
2. Fill in the fields:
   - **Deployment Target**: **Web App (Class + GUI)**. This field only appears when the project could
     also be published as a **Standalone Agent**.
   - **Repository Name**: proposed from the project name in lower case, here `library_app`. Use something unique
     in your account, such as `library-app-lab`.
   - **Description**: defaults to "Web application generated by BESSER".
   - **Make repository private**: leave it off. The dialog warns that private repositories may require
     manual Render permission setup.
3. Click **Publish to Render**. The button reads "Publishing..." while the editor generates the code and
   pushes it.
4. The result dialog is titled **Repository Created Successfully**. It shows `<your-user>/<repository>`, the
   number of files uploaded, and two buttons: **Open Render Deployment** and **View GitHub Repository**.

> **Note**
>
> No screenshots of these two dialogs are included because they only appear after a GitHub sign-in. The
> labels above are taken from the editor's source code (BESSER 8.0).

> **Check your work**
>
> The result dialog says **Repository Created Successfully**, and the repository exists on github.com under
> your account.

### 4. Inspect the generated repository

Click **View GitHub Repository**. The commit pushed by BESSER is called "Initial commit - Generated by
BESSER Web Editor", and the repository contains:

```text
library-app-lab/
├── README.md              overview, project structure and a Deploy to Render button
├── render.yaml            the Render Blueprint
├── docker-compose.yml     the local setup you used in the web-app lab
├── BESSER_GENERATION.md   BESSER version and generator used
├── backend/               FastAPI + SQLAlchemy
├── frontend/              React + TypeScript (Vite)
├── agents/
│   └── greeting_agent/    the BESSER Agentic Framework agent
└── buml/
    ├── domain_model.py    the class diagram as B-UML Python code
    ├── gui_model.py       the GUI model as B-UML Python code
    ├── agent_model_greeting_agent.py
    └── diagrams.json      the project, re-importable in the editor
```

Open `render.yaml`. It declares one service per part of the application. This is its shape (names are
shortened; yours contain the repository name and a six-character suffix):

```text
services:
  # Backend API (Free tier - 750 hours/month, spins down after 15 min idle)
  - type: web
    name: library-app-lab-backend-<suffix>
    runtime: python
    plan: free
    buildCommand: pip install -r backend/requirements.txt
    startCommand: cd backend && uvicorn main_api:app --host 0.0.0.0 --port $PORT

  # Frontend (Free static site)
  - type: web
    name: library-app-lab-frontend-<suffix>
    runtime: static
    buildCommand: cd frontend && npm install && npm run build

  # Agent Service: Greeting_Agent (Free tier - WebSocket-based AI agent)
  - type: web
    name: library-app-lab-greeting-agent-agent-<suffix>
    runtime: python
    plan: free
```

The frontend is built with the backend's and the agent's public `onrender.com` addresses, and the agent's
start command rewrites its `config.yaml` to listen on `0.0.0.0` and Render's port. That is why the
`host: 0.0.0.0` edit from the web-app lab is not needed on Render.

> **Check your work**
>
> You can name the three services the Blueprint will create and find the folders that each one builds from.

### 5. Deploy the Blueprint on Render

1. Back in the editor, click **Open Render Deployment**. It opens Render's deploy page for your repository
   (`https://render.com/deploy?repo=https://github.com/<your-user>/<repository>`). The
   **Deploy to Render** button in the repository's README opens the same page.
2. Sign in to Render (signing in with GitHub is the simplest) and, if Render asks, give it access to the new
   repository.
3. Enter a **Blueprint Name**, keep the **Branch** `main` and the default **Blueprint Path**
   `render.yaml`, review the three services, and click **Deploy Blueprint**.

![Render Blueprint form with Blueprint Name, Branch main, Blueprint Path and three services to create](https://labs.besser-pearl.org/labs/deploy-render/render-blueprint-review.png "Render's own page. Captured from an earlier deployment, so the service names differ from yours")

> **Before you continue**
>
> If Render asks for a value for `OPENAI_API_KEY`, it belongs to the agent service. It is only needed for
> agents that call a language model (LLM-based intent recognition or LLM replies). The Greeting Agent uses
> fixed replies; enter a key only if your own agent needs one, and never commit it to the repository.

4. Wait. On the free plan the three services take between 4 and 12 minutes to build and start. Render shows
   the progress of each service.
5. When all three are live, open the frontend service (its name contains `-frontend-`) and click its
   `onrender.com` address.

The app is the one you ran locally, but empty: the Render backend has its own SQLite database. Add a
library, an author and a book through `https://<backend-service>.onrender.com/docs`, exactly as in the
web-app lab, and reload the frontend.

> **If something goes wrong**
>
> A service that has not been used for 15 minutes sleeps, so the first page load or chat message after a pause
> can take a minute. If the chat widget stays on "Connecting to agent...", open the agent service on Render
> and check that it is live and that its log shows the WebSocket platform starting.

> **Check your work**
>
> The Blueprint shows three services as deployed, the public frontend URL shows the Book page, and the chat
> widget answers "Hello" with "Hi" and "How are you?".

### 6. Extend the domain, the agent and the GUI

The library now needs to track publishers. A publisher has a name, a country and a founding year; it
publishes many books, and each book has one publisher. The application must also compute the average price
of a publisher's books.

1. **Class diagram.** Add a `Publisher` class with `name: str`, `country: str` and `founded: int`. Connect it
   to Book with an association: multiplicity `1` on the Publisher end and `*` on the Book end.
2. Add the method. In the Publisher properties panel, click **Code** under **METHODS**, rename the new method
   to `average_book_price(): float`, set **TYPE** to **Python Code**, and write the body in the
   **Python Implementation** editor:

![Publisher class with name, country and founded, and average_book_price implemented as Python code](https://labs.besser-pearl.org/labs/deploy-render/publisher-method-python.png "A method body can be Python Code or BESSER Action Language; self.books is the association end you just drew")

The code in the screenshot:

```python
def average_book_price(self) -> float:
    if not self.books:
        return 0.0
    return sum(book.price for book in self.books) / len(self.books)
```

Run **Quality Check**. If you prefer the BESSER Action Language, the Library class's `cheapest_book_by`
method is an example of its syntax.

3. **Agent.** Open **Agent** > **Components** and, in the **Intents** section, click **Add Intent**.
   Name it `publisher_price_intent` and use **Add sentence** to add, for example:
   - `how can I get the average price of books from a publisher?`
   - `average book price for a publisher`
   - `how do I compute the publisher average price?`
4. In the Agent diagram, add a state `publisher_help` whose body is a **Text** reply such as "Open the
   Publisher page, select a publisher in the table and click average_book_price." Draw a transition from
   `initial` to `publisher_help`, open it, choose **Intent Matched** and the new intent. Draw a second
   transition from `publisher_help` back to `initial` of type **Auto**.
5. **GUI.** Run **Auto-Generate GUI from Class Diagram** again. It creates the new Publisher page with its
   table and an **average_book_price** button.

> **Before you continue**
>
> Auto-generation rebuilds the whole GUI and removes the BESSER Agent widget and the bar chart you added in the
> web-app lab. Add them again afterwards, and choose `Greeting Agent` in the widget's **Agent** field.

> **Check your work**
>
> Quality Check passes on the Class and Agent diagrams, the **Pages** panel lists Book, Library, Author and
> Publisher, and the Book page has the chat widget again.

### 7. Redeploy and test the changes

1. Choose **Deploy > Publish to Render** again. Because the project is linked to the repository, the dialog
   now says "Update the existing repository with your latest changes.", shows "Previously deployed to:" with
   your repository, and offers a **Commit Message** field (leave it empty for the default
   "Update app - Generated by BESSER Web Editor"). Files you added to the repository by hand are kept.
2. Click **Update & Publish**. The result dialog is titled **Repository Updated Successfully** and offers
   **Open Live App**, **Open Render Blueprint** and **View GitHub Repository**.
3. Render normally redeploys after a push. If your changes do not appear after a few minutes, open the
   Blueprint on Render and click **Manual Sync**: it redeploys every service from the latest commit.
4. Open the live app and check that:
   - the Publisher page exists and you can create a publisher;
   - after you create books for that publisher through the API (the book body now also needs the publisher's
     id; the `BookCreate` schema in Swagger shows the field name), **average_book_price** returns their
     average price;
   - the agent answers "average book price for a publisher" with your instructions.

> **Note**
>
> Choosing "Create new repo instead" in the dialog publishes to a fresh repository and needs a new Blueprint,
> which means three more services in your Render account.

> **Check your work**
>
> The repository has a second commit, the live app shows the Publisher page, and the agent answers the new
> question.

### 8. Exercise: keep evolving the application

> **Exercise: Add a statistics question to the agent**
>
> Add a method `book_count(): int` to Publisher, a matching intent and agent state, and a **Metric Card / KPI**
> or chart on the Publisher page. Publish the update and verify each part in the live app.

<details>
<summary>Show a solution</summary>

`book_count` can reuse the same association end as `average_book_price` (`len(self.books)`). Remember the
order of the GUI work: auto-generate first, then re-add the widgets that auto-generation removes.

</details>

> **Exercise: Publish only the agent**
>
> Open the Agent diagram and choose **Deploy > Publish to Render**. Switch the **Deployment Target** to
> **Standalone Agent** and compare the generated repository and `render.yaml` with the web app's.

<details>
<summary>Show a solution</summary>

The dialog proposes a repository name ending in `-agent`, and the button reads **Publish Agent to Render**.
Look at how many services the agent Blueprint declares and which user interface it starts.

</details>

---

Checked against BESSER 8.0 on 2026-10-02.


<a id="lab-9"></a>

## Lab 9: Build agents with the BESSER Agentic Framework

You generate a database question-answering agent from the editor without code, then write a RAG and LLM agent in Python with BAF.

| Time | Level | Runs with | Do first | Track |
| --- | --- | --- | --- | --- |
| 1 h 15 min | Intermediate | Browser, Python, API key | [Lab 1](https://labs.besser-pearl.org/labs/first-model/) | Conversational agents |

**You'll learn to**

- Generate a runnable BAF agent from an editor template
- Connect a generated agent to a SQLite database and an LLM
- Build a BAF state machine in Python with an LLM intent classifier
- Add RAG over uploaded PDFs and a plain LLM state
- Write a custom message processor

**You'll need**

- A modern browser
- Python 3.11 or 3.12 and about 2 GB of free disk space for the BAF dependencies
- An OpenAI API key with credit (every agent message costs a small amount)
- A short PDF to test with, for example a scientific paper

**Files for this lab**

- [RAG agent starter (Python)](https://labs.besser-pearl.org/files/agents-baf/rag_agent.py)
- [Agent configuration (config.yaml)](https://labs.besser-pearl.org/files/agents-baf/config.yaml)

Online version: https://labs.besser-pearl.org/labs/agents-baf/

---

The [BESSER Agentic Framework](https://besser-agentic-framework.readthedocs.io/latest/) (BAF) is a Python library for agents whose behaviour is a state machine: the agent waits in a state, a user message or event triggers a transition, and the body of the next state runs. States can reply with fixed text, or call an LLM, a database or a retrieval engine.

You use BAF in two ways in this lab. First, with no code: you load the Database Agent template in the Web Modeling Editor, connect it to the Chinook music store database, and generate a BAF project that answers questions about the data. Then, with code: you extend a starter script into an agent that indexes PDFs you upload, answers questions about them with RAG, and handles other instructions with an LLM.

The lab was checked against BAF 4.5.2, the current release on PyPI, whose Python package is `baf`.

> **Before you continue**
>
> Both agents call the OpenAI API with your own key. Each message you send costs money (a few cents for the whole lab with `gpt-4o-mini`, more with larger models or long PDFs). Set a usage limit in your OpenAI account, keep the key out of Git, and stop the agents when you are done.

### 1. Install BAF in a virtual environment

1. Create and activate a virtual environment in a new working folder:

   ```bash
   python -m venv .venv
   source .venv/bin/activate
   ```

   ```powershell
   python -m venv .venv
   .venv\Scripts\Activate.ps1
   ```

2. Install BAF with the `extras` (RAG, vector store, data frames) and `llms` (OpenAI and other clients) options, plus PyMuPDF for reading PDFs:

   ```bash
   pip install "besser-agentic-framework[extras,llms]" pymupdf
   ```

   This does not install PyTorch or TensorFlow. You do not need them, because every agent in this lab classifies intents with an LLM. The `[all]` option in the BAF docs pulls in both and is much larger.

3. Check the installation. Save this as `check_install.py` and run `python check_install.py`:

   ```python
   from importlib.metadata import version
   from baf.core.agent import Agent

   print('BAF', version('besser-agentic-framework'))
   print('Agent created:', Agent('test_agent').name)
   ```

> **Check your work**
>
> The last two lines of the output are:
>
> ```text
> BAF 4.5.2
> Agent created: test_agent
> ```
>
> Two warnings like `besser GUI dependencies could not be imported` may appear first. They are harmless: they only concern GUI features that this lab does not use.

> **If something goes wrong**
>
> `ModuleNotFoundError: No module named 'baf'` means an old BAF (4.2 or earlier, package `besser.agent`) is installed or the virtual environment is not active. Activate `.venv` and run `pip install --upgrade "besser-agentic-framework[extras,llms]"`.

### 2. Load the Database Agent template

1. Open [editor.besser-pearl.org](https://editor.besser-pearl.org/), choose **Start modelling**, name the project `Music Store Agent`, pick the **Agent Developer** perspective and click **Create Project**.
2. In the left sidebar, click **Agent**.
3. Open **File > Load Template**, select the **Agent Diagram** category, select **Database Agent** and click **Load Template**.

![The Database Agent template: an initial state, a db_reply state and two transitions](https://labs.besser-pearl.org/labs/agents-baf/database-agent-diagram.png "Any text message moves the agent from initial to db_reply, which queries the database and returns with an Auto transition")

The `db_reply` state has one action: a database query on the default database in LLM query mode. The LLM turns the user's question into SQL, the agent runs it, and the LLM phrases the result as an answer.

> **Check your work**
>
> The canvas shows the states `initial` and `db_reply`, a transition labelled `ReceiveTextEvent + 0 cond.` and an `Auto` transition back to `initial`.

### 3. Connect an LLM and the Chinook database

The template has no LLM and no database yet. You add both on the **Components** page under **Agent** in the sidebar.

1. Click **Components**, stay on **LLMs** and click **Add LLM**. Enter `gpt-4o-mini` as **Model Name**, keep **Provider** on **OpenAI** and tick **Set as default LLM**.

   ![The LLMs section with one OpenAI LLM named gpt-4o-mini set as default](https://labs.besser-pearl.org/labs/agents-baf/components-llm.png "For OpenAI, the model name is the OpenAI model id")

2. Click **SQL Databases**, then **Add SQL Database**. Enter `db1` as **Name**, choose **SQLite** as **Dialect** and enter `Chinook_Sqlite.sqlite` as **Database file path**.

   ![The SQL Databases section with db1, dialect SQLite and the Chinook file path](https://labs.besser-pearl.org/labs/agents-baf/components-sql-database.png "The name must be db1: the template's Default database setting resolves to db1 in the generated code")

3. Click **Agent Customization**. On the **Agent Runtime** tab, set **Intent Recognition** to **LLM-based** and leave **LLM** on **(use default)**.

   ![Agent Runtime settings: Platform WebSocket, Use Streamlit UI ticked, Intent Recognition LLM-based](https://labs.besser-pearl.org/labs/agents-baf/agent-runtime-llm.png "Classical intent recognition would generate a PyTorch classifier, which you did not install")

> **Check your work**
>
> **Components** shows a 1 next to **LLMs** and next to **SQL Databases**, and **Agent Runtime** shows **LLM-based**.

### 4. Generate and run the Database Agent

1. Click **Agent** in the sidebar so the agent diagram is active, then open **Generate > BESSER Agent**.
2. In the **Select Agent Languages** dialog, leave both language fields empty. **System configuration** shows **WebSocket with Streamlit UI** and **LLM-based**. Click **Generate**.

   ![The Select Agent Languages dialog with the system configuration and the Generate button](https://labs.besser-pearl.org/labs/agents-baf/generate-agent-dialog.png "Adding a spoken language would translate the agent with an LLM during generation; you do not need that here")

3. Unzip the downloaded `agent_output.zip` into a folder. It contains `Database_Agent.py`, `config.yaml`, `agent_model.py`, `readme.txt` and `BESSER_GENERATION.md`.
4. Download `Chinook_Sqlite.sqlite` from the [Chinook releases page](https://github.com/lerocha/chinook-database/releases) (asset of release v1.4.5) into the same folder.
5. Open `config.yaml` and, under `nlp:` > `openai:`, replace `YOUR-API-KEY` with your key. At the end of the file, the `db:` section holds the database you declared:

   ```yaml
   db:
     sql:
       - db1:
           dialect: sqlite
           file: Chinook_Sqlite.sqlite
           host: localhost
           port: 5432
   ```

   BAF opens the SQLite file named by `file`, relative to the folder you run the agent from. SQLite ignores `host` and `port`.

6. From that folder, with your virtual environment active, run the agent:

   ```bash
   python Database_Agent.py
   ```

7. Open http://localhost:5000 and ask, for example, `How many artists are in the database?`.

> **Check your work**
>
> The terminal prints `Database_Agent's WebSocketPlatform starting at ws://localhost:8765` and `You can now view your Streamlit app in your browser.` The answer should mention 275 artists, the number of rows in the `Artist` table. Stop the agent with <kbd>Ctrl+C</kbd>.

> **If something goes wrong**
>
> If every answer is empty or says it cannot find the data, check that `Chinook_Sqlite.sqlite` is in the folder you start the agent from and that its name matches `file:` in `config.yaml` exactly. If the terminal says `Port 5000 is already in use` or cannot bind to port 8765, another program uses those ports. Change `platforms.websocket.port` and `platforms.websocket.streamlit.port` in `config.yaml` and open the new Streamlit port.

### 5. Start the RAG agent from the starter

Now you write an agent yourself. It will have the state machine below: `awaiting_state` is the hub, a PDF upload goes to `load_document_state`, a question goes to `rag_state`, and any other instruction goes to `llm_state`. Every state returns to `awaiting_state`.

1. In a new folder, download [rag_agent.py](https://labs.besser-pearl.org/files/agents-baf/rag_agent.py) and [config.yaml](https://labs.besser-pearl.org/files/agents-baf/config.yaml).
2. Put your OpenAI key in `config.yaml` under `nlp.openai.api_key`.
3. Read `rag_agent.py`. It already:
   - creates `Agent('rag_agent')` and loads `config.yaml`;
   - starts the WebSocket platform with `use_ui=True`, which also serves a Streamlit chat page;
   - creates the OpenAI LLM `gpt-4o-mini`;
   - configures an LLM intent classifier that matches messages by the intent descriptions (`use_intent_descriptions=True`);
   - defines `initial_state` and `awaiting_state`, with a fallback `when_no_intent_matched()` transition back to `awaiting_state`.
4. Run it with `python rag_agent.py` and open http://localhost:5000.

![The Streamlit chat page of rag_agent with the greeting](https://labs.besser-pearl.org/labs/agents-baf/rag-agent-chat.png "The greeting comes from awaiting_state; the sidebar has the file upload you use next")

> **Check your work**
>
> The chat shows `Hi! Upload a PDF, ask me a question about it, or give me an instruction.` Stop the agent with <kbd>Ctrl+C</kbd> before you edit the file.

### 6. Add the RAG component and PDF upload

RAG needs three parts: a text splitter that cuts documents into chunks, a vector store that keeps an embedding of each chunk, and an LLM that writes the answer from the retrieved chunks.

1. Add these imports at the top of `rag_agent.py`:

   ```python
   from baf.nlp.rag.rag import RAG, RAGMessage
   from langchain_community.embeddings import OpenAIEmbeddings
   from langchain_community.vectorstores import Chroma
   from langchain_text_splitters import RecursiveCharacterTextSplitter
   ```

2. Replace the `# TODO: splitter, vector store and RAG go here` line with the RAG setup. The embeddings reuse the key from `config.yaml`:

   ```python
   embeddings = OpenAIEmbeddings(openai_api_key=agent.get_property(nlp.OPENAI_API_KEY))
   vector_store = Chroma(embedding_function=embeddings, persist_directory='vector_store')
   splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=100)
   rag = RAG(
       agent=agent,
       vector_store=vector_store,
       splitter=splitter,
       llm_name='gpt-4o-mini',
       k=4,                     # number of chunks to retrieve
       num_previous_messages=0  # chat history added to the prompt
   )
   ```

3. Replace the `# TODO: create load_document_state, rag_state and llm_state` line:

   ```python
   load_document_state = agent.new_state('load_document_state')
   rag_state = agent.new_state('rag_state')
   llm_state = agent.new_state('llm_state')
   ```

4. Make a PDF upload move the agent from `awaiting_state` to `load_document_state`. Put this line just before the existing `when_no_intent_matched()` transition, then add the body of the new state. `rag.add_file` reads the uploaded file, splits it and stores the chunks:

   ```python
   awaiting_state.when_file_received(allowed_types='application/pdf').go_to(load_document_state)

   def load_document_body(session: Session):
       n_chunks = rag.add_file(session.event.file)
       session.reply(f'Document loaded ({n_chunks} chunks).')

   load_document_state.set_body(load_document_body)
   load_document_state.go_to(awaiting_state)
   ```

5. Run the agent and upload your PDF with **Browse files** in the chat sidebar.

> **Check your work**
>
> The agent replies `Document loaded (N chunks).` and the terminal logs `[RAG] Added N chunks from '<your file>.pdf' to RAG's vector store.` A `vector_store` folder appears next to the script.

> **Note**
>
> The vector store persists between runs. Uploading the same PDF twice stores its chunks twice. Delete the `vector_store` folder to start again from an empty store.

### 7. Answer questions with RAG and instructions with the LLM

The LLM intent classifier decides between two intents using only their descriptions.

1. Replace the `# TODO: create question_intent and instruction_intent` line:

   ```python
   question_intent = agent.new_intent(
       'question_intent',
       description='The message is a question, finishing with a question mark (?)'
   )
   instruction_intent = agent.new_intent(
       'instruction_intent',
       description='The message is an instruction. Do not consider questions as instructions.'
   )
   ```

2. Add the two intent transitions next to the file transition, before `when_no_intent_matched()`, which now catches everything else:

   ```python
   awaiting_state.when_intent_matched(question_intent).go_to(rag_state)
   awaiting_state.when_intent_matched(instruction_intent).go_to(llm_state)
   ```

3. Add the bodies. The RAG state retrieves chunks and lets the WebSocket platform show the answer with its sources. The LLM state sends the message straight to the model:

   ```python
   def rag_body(session: Session):
       rag_message: RAGMessage = session.run_rag(session.event.message)
       websocket_platform.reply_rag(session, rag_message)

   rag_state.set_body(rag_body)
   rag_state.go_to(awaiting_state)

   def llm_body(session: Session):
       answer = gpt.predict(session.event.message)
       session.reply(answer)

   llm_state.set_body(llm_body)
   llm_state.go_to(awaiting_state)
   ```

4. Run the agent. Ask a question about your PDF that ends with `?`, then send an instruction such as `Write a haiku about state machines.`

> **Check your work**
>
> The terminal logs the transition for each message: the question produces a line ending in `[awaiting_state] --> [rag_state]`, the instruction one ending in `[awaiting_state] --> [llm_state]`. The RAG answer refers to your document and has a **Details** expander that lists the retrieved chunks with their source file and page.

> **If something goes wrong**
>
> `openai.AuthenticationError` or `RateLimitError` in the terminal comes from OpenAI, not from BAF: the key in `config.yaml` is wrong, or the account has no credit left. `AttributeError: 'Session' object has no attribute 'message'` means code copied from an older BAF guide: use `session.event.message` and `session.event.file`.

### 8. Exercise: write a custom processor

A [processor](https://besser-agentic-framework.readthedocs.io/latest/wiki/core/processors.html) transforms every user message, every agent message, or both, before the state machine or the user sees it. BAF ships a language detection processor and an LLM-based user adaptation processor in `baf.core.processors`.

> **Exercise: Normalize internet slang**
>
> Add a processor to the RAG agent that rewrites slang in user messages before intent classification, so `idk who r u` reaches the classifier as `I don't know who are you`. Then pick a second idea and build it: a sentiment processor that stores `positive`, `neutral` or `negative` in the session, or a translator for agent replies.

<details>
<summary>Show a solution</summary>

Subclass `baf.core.processors.processor.Processor`. Call `super().__init__(agent=agent, user_messages=True)` and implement `process(self, session, message) -> str`, returning the rewritten message. Creating the processor object is enough to register it with the agent. A dictionary lookup over the words of the message is enough for the slang case; store results with `session.set('sentiment', ...)` for the sentiment case.

</details>

> **Exercise: Show raw database results as a table**
>
> The generated Database Agent asks the LLM to phrase every result as a sentence. Change `db_reply_body` in `Database_Agent.py` so that it shows the rows returned by `session.db_handler.select(...)` as a table instead.

<details>
<summary>Show a solution</summary>

Convert the result to a pandas `DataFrame`: a list of dicts becomes one row per dict, a single dict becomes one row, and a single value becomes a one-cell frame. Send it with `platform.reply_dataframe(session, df)` instead of the second LLM call. Keep the first call with `llm=default_llm`, which turns the question into SQL.

</details>

---

Checked against BESSER 8.0 on 2026-10-02.


<a id="lab-10"></a>

## Lab 10: Personalize an agent for its users

You model two user profiles, adapt the Gym Agent to each of them in the editor, and generate one agent that switches behaviour per profile.

| Time | Level | Runs with | Do first | Track |
| --- | --- | --- | --- | --- |
| 55 min | Intermediate | Browser, Python, Docker, API key | [Lab 1](https://labs.besser-pearl.org/labs/first-model/) | Conversational agents |

**You'll learn to**

- Describe a user group as a User diagram with matching criteria
- Configure presentation, modality and content per user profile on the Agent Customization page
- Switch between the base agent and its personalized variants
- Generate one agent that serves several profiles and run it with its user database

**You'll need**

- A modern browser
- Only to run the agent: Python 3.11 or 3.12 with BAF installed, Docker, and an OpenAI API key with credit

**Files for this lab**

- [Agent configuration for the personalized agent (config.yaml)](https://labs.besser-pearl.org/files/agent-personalization/config.yaml)
- [PostgreSQL database for logins and sessions (Dockerfile)](https://labs.besser-pearl.org/files/agent-personalization/Dockerfile)

Online version: https://labs.besser-pearl.org/labs/agent-personalization/

---

A company builds digital assistants for fitness centres. Its Gym Agent greets the user, waits for a question, sorts it into training, nutrition or other, gives a generic answer and goes back to waiting. That works for an average visitor, but not for everyone: an elderly visitor may prefer spoken interaction and larger text, and a visitor who uses a wheelchair needs workouts that do not rely on the legs.

In this lab you model those two users and let BESSER adapt the agent to each. You describe each profile in a User diagram, attach a customization to it on the Agent Customization page, and generate a single agent that asks the user for their profile and then runs the matching variant. The editor part needs only a browser. Running the agent is optional and needs Python, Docker and an OpenAI key.

The lab assumes you know the editor basics from [Your first class diagram](https://labs.besser-pearl.org/labs/first-model/). [Build agents with the BESSER Agentic Framework](https://labs.besser-pearl.org/labs/agents-baf/) explains how the generated agent code works, but you do not need it here.

### 1. Load the Gym Agent and inspect it

1. Open [editor.besser-pearl.org](https://editor.besser-pearl.org/), choose **Start modelling**, name the project `Gym Coach`, pick the **Agent Developer** perspective and click **Create Project**. The sidebar now shows **Agent** and **User**.
2. Click **Agent**, then open **File > Load Template**, select the **Agent Diagram** category, select **Gym Agent** and click **Load Template**.
3. Zoom out with the **-** button at the bottom right until you see the whole diagram.

![The Gym Agent: Initial, Idle, TrainingPlan, Nutrition and OtherQuestions states connected by Auto and intent transitions](https://labs.besser-pearl.org/labs/agent-personalization/gym-agent-diagram.png "Idle is the hub: an intent sends the agent to an answer state, and an Auto transition brings it back")

Read the diagram:

- **States** are the rounded boxes. Each row under the name is one reply the agent sends when it enters the state. `Idle` has a second, fallback reply for messages that match no intent. `OtherQuestions` has a single **AI response** row: an LLM answers.
- **Transitions** are the arrows. `Auto` fires as soon as the state has replied. `Muscles_intent`, `Nutrition_intent` and `Other` fire when the user's message matches that intent.

4. Click **Components** under **Agent** and open **Intents**. Expand **Muscles_intent**.

![The Intents section with Muscles_intent expanded: its description and the training sentence I want muscles](https://labs.besser-pearl.org/labs/agent-personalization/components-intents.png "Intents live on the Components page, not on the canvas")

> **Check your work**
>
> The canvas shows five states and the **Intents** section lists three intents: `Muscles_intent`, `Nutrition_intent` and `Other`, each with a description.

### 2. Check the agent's LLM

The template uses an LLM in two places: to classify messages into intents and to answer in `OtherQuestions`. The personalized variants also pass their profile to this LLM. The template already declares it; check it before you create variants.

1. On **Components**, open **LLMs**. It lists one LLM, `gpt-4o-mini` with the provider `openai`. Click its name to see its settings.

   ![The LLMs section with one OpenAI LLM named gpt-4o-mini, Set as default LLM unticked](https://labs.besser-pearl.org/labs/agent-personalization/components-llm.png "For OpenAI, the model name is the OpenAI model id")

   You do not need to tick **Set as default LLM**: when the agent has a single LLM, the generated code uses it as the default.

2. Click **Agent Customization** under **Agent**. On the **Agent Runtime** tab, set **Intent Recognition** to **LLM-based**. Keep **Platform** on **WebSocket** with **Use Streamlit UI** ticked.

   ![The Agent Runtime tab with Platform WebSocket, Use Streamlit UI and Intent Recognition LLM-based](https://labs.besser-pearl.org/labs/agent-personalization/customization-runtime.png "LLM-based recognition matches messages by the intent descriptions you just read")

> **Check your work**
>
> **LLMs** shows a 1 and lists `gpt-4o-mini`, and **Agent Runtime** shows **LLM-based**.

### 3. Model the Elderly profile

A User diagram describes a group of users by criteria on a fixed user model: `User` is the root, with parts such as `Personal_Information`, `Accessibility`, `Competence` and `Culture`. You can drag these parts from the palette and link them, but the form editor is faster and cannot produce an invalid structure.

1. Click **User** in the sidebar. The palette on the left lists **User**, **Personal_Information**, **Competence**, **Accessibility**, **Culture**, **Language** and more.
2. Click **Edit as Form** at the top right. The **User Profile Form** opens with **User** as **ROOT**.
3. Tick **Include** next to **Personal Information**, then click **Personal Information** to expand it.
4. In the `age` row, choose `>` in the operator list and enter `65`. Leave the other fields empty: an empty field is not a criterion.

   ![The User Profile Form with Personal Information included and age > 65](https://labs.besser-pearl.org/labs/agent-personalization/user-form-elderly.png "Only numeric fields get an operator; text and enumeration fields always mean equals")

5. Close the form with the cross at its top right.
6. Double-click the diagram tab **User Diagram**, type `Elderly` and press <kbd>Enter</kbd>.
7. Click **Quality Check** in the top bar.

> **Check your work**
>
> The tab is named `Elderly`. **Quality Check** reports **Valid Constraints** with the constraint `pi_age_range` evaluating to `True`.

> **Note**
>
> **Quality Check** also shows warnings that start with `Mandatory creation cycle: Input_Modality -> Interaction_Modality`. They concern the built-in user model, not your profile, and you can ignore them. If you leave a User diagram without checking it, the editor asks you to **Validate models** first; choose that option.

### 4. Model the Paraplegic profile

1. Click **+** next to the `Elderly` tab to add a second User diagram.
2. Click **Edit as Form**, tick **Include** next to **Accessibility** and expand it.
3. Next to **Disability**, click **Add**, then click **Disability** to expand it.
4. Fill in **Disability 1**: `name` = `Paraplegic`, `description` = `Cannot use lower body`, and choose `Mobility` for `affects`.

   ![The User Profile Form with Accessibility included and one Disability: Paraplegic, Cannot use lower body, Mobility](https://labs.besser-pearl.org/labs/agent-personalization/user-form-paraplegic.png "affects is an enumeration of the user model, so it is a dropdown")

5. Close the form, rename the tab to `Paraplegic` and click **Quality Check**.

> **Check your work**
>
> There are two User diagram tabs, `Elderly` and `Paraplegic`, and the sidebar shows **User (2)**. **Quality Check** reports the constraint `disability_description_not_empty` as `True`.

### 5. Customize the agent for the Elderly profile

1. Click **Agent**, then **Agent Customization**, and switch to the **Personalization** tab.
2. Under **User Profile Mapping**, choose `Elderly`.

   ![The Personalization tab with Elderly selected under User Profile Mapping and the three automatic proposal buttons](https://labs.besser-pearl.org/labs/agent-personalization/customization-profile-mapping.png "The list shows one entry per User diagram tab")

   The three **Automatically propose configuration using ...** buttons fill the form for you, from predefined rules, an LLM or a RAG source. They need a GitHub sign-in (**GitHub** button in the top bar); without one they show `Sign in to GitHub to use recommendations.` You can skip them and set the values by hand.

3. Under **Personalization Overview**, click **Presentation**. Set **Style** to **Formal**. Under **Style of text in interface**, set **Size** to `20` and **Contrast** to **High**.

   ![The Presentation section with Style Formal, Size 20 and Contrast High; Language, Language Complexity and Sentence Length on Original](https://labs.besser-pearl.org/labs/agent-personalization/customization-presentation.png "Style rewrites the agent's fixed replies; size and contrast change the chat interface")

   **Language**, **Style**, **Language Complexity** and **Sentence Length** rewrite every fixed reply with an LLM on the BESSER server when you apply.

4. Click **Modality** and tick **Enable speech input** and **Enable speech output**.

   ![The Modality section with speech input and speech output enabled](https://labs.besser-pearl.org/labs/agent-personalization/customization-modality.png "Text input and output stay enabled; speech is added on top")

5. Scroll to **Save this customization**, enter `Elderly` as **Customization Name** and click **Save & Apply Configuration**.

   ![The Save this customization card with the name Elderly and the Save & Apply Configuration button](https://labs.besser-pearl.org/labs/agent-personalization/customization-save.png "Saved customizations appear in the picker at the top of the page")

> **Check your work**
>
> A toast says `Configuration transformed, saved, and applied successfully.` and the editor returns to the agent diagram. The variant selector in the top bar, which showed `Base agent model`, now also offers `Elderly (Elderly)`.

> **If something goes wrong**
>
> The server-side rewrite takes from a few seconds to a few minutes, and the page shows `Working on it...` meanwhile. Wait for the toast. If it shows `Failed to transform agent model` instead, the server could not complete the rewrite: set the four text lists back to **Original** and apply again. Size, contrast and speech do not need the server LLM.

### 6. Customize the agent for the Paraplegic profile

1. Open **Agent Customization** > **Personalization** again. Under **User Profile Mapping**, choose `Paraplegic`.
2. Click **Content** and tick **Adapt content to user profile**.

   ![The Content section with Adapt content to user profile ticked](https://labs.besser-pearl.org/labs/agent-personalization/customization-content.png "The profile chosen in User Profile Mapping is the one used for adaptation")

3. Enter `Paraplegic` as **Customization Name** and click **Save & Apply Configuration**.
4. Use the variant selector in the top bar to switch between `Base agent model`, `Elderly (Elderly)` and `Paraplegic (Paraplegic)`. Each entry is a separate copy of the agent diagram; the base model stays untouched.

> **Check your work**
>
> The variant selector lists three entries: `Base agent model`, `Elderly (Elderly)` and `Paraplegic (Paraplegic)`.

> **Note**
>
> With content adaptation, **Save & Apply Configuration** rewrites the fixed replies of the variant for the profile, and the generated agent also hands the profile to its LLM as context, so LLM answers take the disability into account. Switch to `Paraplegic (Paraplegic)` and open `TrainingPlan`: the first reply no longer suggests squats and deadlifts but upper-body lifts you can do seated or supported. The exact wording comes from an LLM and differs from run to run. In `Elderly (Elderly)`, the replies keep their content but are rewritten in a formal style.

### 7. Generate the personalized agent

1. Select `Base agent model` in the variant selector, so the agent diagram is active.
2. Open **Generate > BESSER Agent**.
3. In the **Select Agent Languages** dialog, under **Personalization Strategy**, choose **Personalization (all)** and click **Generate**.

   ![The Select Agent Languages dialog with Personalization Strategy set to Personalization (all)](https://labs.besser-pearl.org/labs/agent-personalization/generate-agent-personalization.png "None would generate only the base agent")

4. Unzip the downloaded `agent_output.zip`.

> **Check your work**
>
> The folder contains `Gym_Agent.py`, `config.yaml`, `user_profiles.json`, `agent_model.py`, `readme.txt` and `BESSER_GENERATION.md`. `Gym_Agent.py` defines the base states plus a copy per profile, such as `Initial_Elderly` and `TrainingPlan_Paraplegic`, and a `router_initial_state` that jumps to the copy matching the user's profile.

### 8. Run the agent with its user database

The personalized agent asks every user to log in and to pick a profile, and stores users and sessions in PostgreSQL. You run that database in Docker.

> **Before you continue**
>
> The agent calls the OpenAI API with your key for intent classification, for `OtherQuestions`, and for speech in the Elderly variant. Every message costs a small amount. Keep the key out of Git and stop the agent when you are done.

1. Install BAF if you have not yet, in a virtual environment: `pip install "besser-agentic-framework[extras,llms]"` (see [Build agents with the BESSER Agentic Framework](https://labs.besser-pearl.org/labs/agents-baf/)).
2. In a separate folder, download the [Dockerfile](https://labs.besser-pearl.org/files/agent-personalization/Dockerfile) and start the database:

   ```bash
   docker build -t agentdb .
   docker run -d --name agentdb -p 5432:5432 agentdb
   ```

3. Download [config.yaml](https://labs.besser-pearl.org/files/agent-personalization/config.yaml) and use it to replace the generated `config.yaml` in the unzipped agent folder. It enables the `monitoring` and `streamlit` databases with the credentials of the Dockerfile. Replace `YOUR-API-KEY` with your OpenAI key.
4. From the agent folder, run:

   ```bash
   python Gym_Agent.py
   ```

5. Open http://localhost:5000. Enter any username and password and click **Login**: an unknown username creates a new account.
6. Click **Choose Your User Profile**, flip to the profile you want with **Next >**, click **Confirm as fitting to me**, then click **Chat with Agent**.

![The profile picker showing the Paraplegic card with its disability and the Confirm as fitting to me button](https://labs.besser-pearl.org/labs/agent-personalization/run-profile-picker.png "The cards come from user_profiles.json, which BESSER built from your User diagrams")

![The chat page with Selected profile: Paraplegic and the two greeting messages](https://labs.besser-pearl.org/labs/agent-personalization/run-chat.png "The greeting comes from Initial_Paraplegic and Idle_Paraplegic")

> **Check your work**
>
> After you confirm the Paraplegic profile, the chat shows `Selected profile: Paraplegic` and the replies `Hi, I am your buddy, the fitness agent.` and `I am here to answer any questions regarding exercises, nutrition and recovery.` The terminal logs `Session variable user_profile set to Paraplegic.` Now ask a question that no intent covers, such as `How should I warm up before a session?`: `OtherQuestions` answers with the LLM, which receives the Paraplegic profile as context. Stop the agent with <kbd>Ctrl+C</kbd> and the database with `docker stop agentdb`.

> **If something goes wrong**
>
> `Port 5000 is already in use`, or an error about binding to port 8765, means another program uses those ports. Change `platforms.websocket.port` and `platforms.websocket.streamlit.port` in `config.yaml` and open the new Streamlit port. If the login page shows a database error, check that `docker ps` lists `agentdb` with port 5432.

### 9. Exercise: add a third user group

> **Exercise: Teenage members**
>
> Add a `Teenager` profile for users younger than 18, and a customization that suits them: informal style, abbreviations, and a font and colour of your choice. Regenerate with **Personalization (all)** and check that the profile picker now shows three cards.

<details>
<summary>Show a solution</summary>

Add a third User diagram tab with `Personal Information` included and `age` `<` `18`, then save a customization mapped to it. For comparison, **File > Load Template** > **Full Project** > **Personalized Gym Agent** opens a ready-made project (as a new project) with a `Teenager` and a `ParaplegicUser` profile.

</details>

> **Exercise: Change the base agent and re-personalize**
>
> Add a `Recovery_intent` and a `Recovery` state with two replies about rest days and sleep, connected like `Nutrition`. Bring both variants up to date and regenerate.

<details>
<summary>Show a solution</summary>

Edit the `Base agent model`: add the intent on **Components** > **Intents**, then the state and its transitions on the canvas. A variant is a snapshot taken at **Save & Apply Configuration** time, and the editor re-personalizes from its stored copy of the base model, which it refreshes when you switch variants. So switch to a variant and back to `Base agent model`, load each saved customization with **Load a saved customization**, apply it again, and regenerate.

</details>

---

Checked against BESSER 8.0 on 2026-10-02.


<a id="lab-11"></a>

## Lab 11: Write your own code generator

A working BESSER generator that turns a B-UML class model into Ruby on Rails model classes.

| Time | Level | Runs with | Do first | Track |
| --- | --- | --- | --- | --- |
| 1 h | Intermediate | Python | [Lab 2](https://labs.besser-pearl.org/labs/buml-python/) | Extend BESSER |

**You'll learn to**

- Implement a generator class on top of BESSER's GeneratorInterface
- Load and render a Jinja template the way the built-in generators do
- Traverse classes, attributes and association ends of a domain model from a template
- Map multiplicities to Rails associations (has_many, belongs_to, has_and_belongs_to_many)

**You'll need**

- Python 3.11 or 3.12
- A terminal and a code editor
- Basic Jinja or other template syntax helps but is not required

**Files for this lab**

- [Generator class (rails_generator.py)](https://labs.besser-pearl.org/files/code-generator/rails_generator.py)
- [Starter template (rails_models.rb.j2)](https://labs.besser-pearl.org/files/code-generator/rails_models.rb.j2)
- [Library model (library_model.py)](https://labs.besser-pearl.org/files/code-generator/library_model.py)
- [Run script (generate.py)](https://labs.besser-pearl.org/files/code-generator/generate.py)

Online version: https://labs.besser-pearl.org/labs/code-generator/

---

Every BESSER generator follows the same recipe: a Python class receives a B-UML model, a Jinja template walks through that model, and the rendered text is written to a file. Once you know the recipe, you can target any language or framework BESSER does not support yet.

In this lab you build a generator for Ruby on Rails. Rails follows the Model-View-Controller pattern, and you generate the Model part: one `ApplicationRecord` class per B-UML class, with its attributes and its associations. You work with the same Library, Book and Author model used in earlier labs.

You do not need Ruby or Rails installed. The generator only writes text; checking it with Ruby is optional.

### 1. Set up the project folder

1. Create a folder for the generator and a virtual environment with BESSER in it.

   ```bash
   mkdir rails-generator
   cd rails-generator
   python -m venv .venv
   source .venv/bin/activate
   python -m pip install besser
   ```

   ```powershell
   mkdir rails-generator
   cd rails-generator
   python -m venv .venv
   .venv\Scripts\Activate.ps1
   python -m pip install besser
   ```

2. Download the four starter files from the top of this page. Put [rails_generator.py](https://labs.besser-pearl.org/files/code-generator/rails_generator.py), [library_model.py](https://labs.besser-pearl.org/files/code-generator/library_model.py) and [generate.py](https://labs.besser-pearl.org/files/code-generator/generate.py) in `rails-generator/`. Create a `templates/` folder and put [rails_models.rb.j2](https://labs.besser-pearl.org/files/code-generator/rails_models.rb.j2) in it.

   ```text
   rails-generator/
   ├── generate.py
   ├── library_model.py
   ├── rails_generator.py
   └── templates/
       └── rails_models.rb.j2
   ```

3. Check the installed version:

   ```bash
   python -c "from importlib.metadata import version; print(version('besser'))"
   ```

   ```text
   8.0.1
   ```

`library_model.py` builds this model with the B-UML Python API:

| Class | Attributes | Associations |
|---|---|---|
| Library | name: str, address: str | `locatedIn` 1 on the Library side, `has` 0..* on the Book side |
| Book | title: str, pages: int, release: datetime | `publishes` 0..* on the Book side, `writtenBy` 1..* on the Author side |
| Author | name: str, email: str | |

> **Check your work**
>
> The four files are in place, `templates/` holds the `.j2` file, and the version command prints `8.0.1` (or a later 8.x release).

### 2. Read the generator class

Open `rails_generator.py`. Without its docstrings, this is the whole generator:

```python
import os

from jinja2 import Environment, FileSystemLoader

from besser.BUML.metamodel.structural import DomainModel
from besser.generators import GeneratorInterface
from besser.utilities import sort_by_timestamp

class RailsGenerator(GeneratorInterface):

    def __init__(self, model: DomainModel, output_dir: str = None):
        super().__init__(model, output_dir)

    def generate(self):
        file_path = self.build_generation_path(file_name="models.rb")
        templates_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "templates")
        env = Environment(loader=FileSystemLoader(templates_path),
                          trim_blocks=True, lstrip_blocks=True)
        env.globals["sort_by_timestamp"] = sort_by_timestamp
        template = env.get_template("rails_models.rb.j2")
        with open(file_path, mode="w", encoding="utf-8") as f:
            f.write(template.render(model=self.model))
        print("Code generated in the location: " + file_path)
```

What each piece does:

- `GeneratorInterface` (in `besser/generators/generator_interface.py`) is an abstract base class with two abstract methods: `__init__(self, model, output_dir=None)` and `generate(self)`. Calling `super().__init__` stores the model in `self.model` and the folder in `self.output_dir`.
- `build_generation_path("models.rb")` is a helper from the interface. It creates `output_dir`, or `./output` when you passed none, and returns the full path of the file to write.
- The Jinja `Environment` loads templates from the `templates/` folder next to the generator file, so the generator works from any working directory. The built-in generators, for example `besser/generators/java_classes/java_generator.py`, use the same pattern with `trim_blocks` and `lstrip_blocks`, which stop `{% %}` lines from leaving blank lines and indentation in the output.
- `env.globals["sort_by_timestamp"]` makes a BESSER helper available inside the template. You will see why it matters in the next step.
- `template.render(model=self.model)` exposes the domain model to the template as `model`.

> **Note**
>
> The BESSER documentation page on creating a generator shows `self.render_template(...)` and `self.write_file(...)`. Those methods do not exist on `GeneratorInterface` in 8.0.1. Load the template with Jinja and write the file yourself, as above.

> **Check your work**
>
> You can say which line decides the output file name (`build_generation_path`), which line picks the template (`get_template`) and which name the template uses for the model (`model`).

### 3. Write a first template that lists the classes

Open `templates/rails_models.rb.j2`:

```jinja
{% for class in sort_by_timestamp(model.get_classes()) %}
class {{ class.name }} < ApplicationRecord
end

{% endfor %}
```

`model.get_classes()` returns a Python `set`, so its order changes from run to run. On one run it came back as:

```python
>>> [c.name for c in library_model.get_classes()]
['Author', 'Book', 'Library']
```

Every B-UML element records when it was created, and `sort_by_timestamp` turns the set into a list in creation order. The built-in generators use it for the same reason: the same model always produces the same file, so diffs between two generations stay meaningful.

> **Check your work**
>
> The template loops over the sorted classes and prints a `class ... < ApplicationRecord` / `end` pair for each one.

### 4. Run the generator on the Library model

`generate.py` imports the model and calls the generator:

```python
from library_model import library_model
from rails_generator import RailsGenerator

RailsGenerator(model=library_model).generate()
```

Run it from the `rails-generator/` folder:

```bash
python generate.py
```

```text
Code generated in the location: /path/to/rails-generator/output/models.rb
```

Open `output/models.rb`:

```ruby
class Library < ApplicationRecord
end

class Book < ApplicationRecord
end

class Author < ApplicationRecord
end
```

Pass `output_dir` to write somewhere else, for example straight into a Rails project: `RailsGenerator(model=library_model, output_dir="app/models").generate()`.

> **If something goes wrong**
>
> `jinja2.exceptions.TemplateNotFound: rails_models.rb.j2` means the template is not inside a `templates/` folder next to `rails_generator.py`. Check the folder name and that the file did not get a `.txt` extension from the browser download.

> **Check your work**
>
> `output/models.rb` lists Library, Book and Author in that order, and running `python generate.py` again gives the same file.

### 5. Add attributes with a type mapping

Rails needs a type for each attribute. B-UML primitive types have short names: `StringType.name` is `str`, and the others are `int`, `float`, `bool`, `date`, `datetime` and `time`. Map them to Rails types with a dictionary at the top of the template, and loop over each class's attributes:

```jinja
{% set rails_types = {"str": "string", "int": "integer", "float": "float", "bool": "boolean",
                      "date": "date", "datetime": "datetime", "time": "time"} %}
{% for class in sort_by_timestamp(model.get_classes()) %}
class {{ class.name }} < ApplicationRecord
{% for attr in sort_by_timestamp(class.attributes) %}
  attribute :{{ attr.name }}, :{{ rails_types.get(attr.type.name, "string") }}
{% endfor %}
end

{% endfor %}
```

`class.attributes` is also a set, so it gets the same sorting. Types that are not in the dictionary, such as an enumeration, fall back to `string`.

Run `python generate.py` again:

```ruby
class Library < ApplicationRecord
  attribute :name, :string
  attribute :address, :string
end

class Book < ApplicationRecord
  attribute :title, :string
  attribute :pages, :integer
  attribute :release, :datetime
end

class Author < ApplicationRecord
  attribute :name, :string
  attribute :email, :string
end
```

> **Check your work**
>
> Each class lists its attributes in the order they were declared in `library_model.py`, with `:integer` for `pages` and `:datetime` for `release`.

### 6. Explore how the model exposes associations

Before you generate associations, look at what the model gives you. Create `explore_associations.py` in the project folder:

```python
from besser.utilities import sort_by_timestamp
from library_model import library_model

for cls in sort_by_timestamp(library_model.get_classes()):
    print(cls.name)
    for end in sort_by_timestamp(cls.association_ends()):
        mine = end.opposite_end()
        print(f"  via {end.owner.name}: this side '{mine.name}' {mine.multiplicity.min}..{mine.multiplicity.max}, "
              f"other side '{end.name}' -> {end.type.name} {end.multiplicity.min}..{end.multiplicity.max}, "
              f"navigable={end.is_navigable}")
```

Run it with `python explore_associations.py`:

```text
Library
  via lib_book_assoc: this side 'locatedIn' 1..1, other side 'has' -> Book 0..9999, navigable=True
Book
  via lib_book_assoc: this side 'has' 0..9999, other side 'locatedIn' -> Library 1..1, navigable=True
  via book_author_assoc: this side 'publishes' 0..9999, other side 'writtenBy' -> Author 1..9999, navigable=True
Author
  via book_author_assoc: this side 'writtenBy' 1..9999, other side 'publishes' -> Book 0..9999, navigable=True
```

What this tells you about the API:

- An association end is a `Property`. Its `type` is the class at that end, and its `owner` is the `BinaryAssociation` it belongs to.
- `cls.association_ends()` returns the ends at the other side of each of the class's associations, the ones you navigate to from `cls`. For Book that is `locatedIn` (to Library) and `writtenBy` (to Author).
- `end.opposite_end()` returns the end on the class's own side of the same association.
- `end.multiplicity.min` and `end.multiplicity.max` are integers. An unbounded `"*"` is stored as `9999`, so test `max > 1` for "many", not `max == "*"`.
- `end.is_navigable` is `False` when the association cannot be traversed in that direction. Skip those ends in generated code.
- `cls.associations` returns the associations themselves, and `association.ends` returns both ends.

> **Note**
>
> `cls.association_ends()` only covers associations declared on the class itself. Use `cls.all_association_ends()` when a subclass should also see the associations of its parents.

> **Check your work**
>
> The script prints two ends for Book and one each for Library and Author, and you can read off, for every end, the multiplicity on both sides.

### 7. Exercise: generate Rails associations and validations

> **Exercise: Generate has_many, belongs_to and has_and_belongs_to_many**
>
> Extend `rails_models.rb.j2` so that the generator writes the associations as well. For the Library model, `output/models.rb` must match this file exactly:
>
> ```ruby
> class Library < ApplicationRecord
>   attribute :name, :string
>   attribute :address, :string
>   has_many :books
> end
>
> class Book < ApplicationRecord
>   attribute :title, :string
>   attribute :pages, :integer
>   attribute :release, :datetime
>   belongs_to :library
>   has_and_belongs_to_many :authors
> end
>
> class Author < ApplicationRecord
>   attribute :name, :string
>   attribute :email, :string
>   has_and_belongs_to_many :books
> end
> ```
>
> Rails names associations after the target class: plural for "many" (`:books`), singular for "one" (`:library`). If you have Ruby installed, `ruby -c output/models.rb` should print `Syntax OK`.

<details>
<summary>Show a solution</summary>

Add a second inner loop after the attributes: `{% for end in sort_by_timestamp(class.association_ends()) if end.is_navigable %}`. Inside it, compare `end.multiplicity.max` with `end.opposite_end().multiplicity.max`. Many on both sides gives `has_and_belongs_to_many`. Many on the other side only gives `has_many`. One on the other side and many on this side gives `belongs_to`. Build the name with `end.type.name | lower`, adding an `s` for the plural forms. Watch the blank line between classes: `loop.last` helps you avoid a trailing one.

</details>

> **Exercise: Generate validations from the model**
>
> Make the generator write Rails validations. Every attribute that is not optional (`attr.is_optional` is `False`) gets `validates :<name>, presence: true`. An attribute marked as an external identifier (`is_external_id=True`, a user-facing key such as an ISBN) also gets `uniqueness: true`. Test it by setting `is_external_id=True` on `Book.title` and `is_optional=True` on `Author.email` in `library_model.py`.

<details>
<summary>Show a solution</summary>

Add one more loop over `sort_by_timestamp(class.attributes)` with the filter `if not attr.is_optional`, and append `, uniqueness: true` inside `{% if attr.is_external_id %}`. With the two model changes, Book should get `validates :title, presence: true, uniqueness: true` and Author should get no validation for `email`.

</details>

To make your generator available in the Web Modeling Editor's **Generate** menu, it has to be registered in a BESSER source checkout: in `SUPPORTED_GENERATORS` in `besser/utilities/web_modeling_editor/backend/config/generators.py`, plus a menu entry in the editor frontend, followed by running the editor locally. The [generator guide](https://besser.readthedocs.io/en/latest/generators/build_generator.html) covers the backend part. [Extend the B-UML metamodel](https://labs.besser-pearl.org/labs/metamodel-extension/) shows how to set up the source checkout.

---

Checked against BESSER 8.0 on 2026-10-02.


<a id="lab-12"></a>

## Lab 12: Extend the B-UML metamodel and a generator

A BESSER source checkout where Property has a new max_length concept, the SQLAlchemy generator uses it, and a pytest test proves it.

| Time | Level | Runs with | Do first | Track |
| --- | --- | --- | --- | --- |
| 1 h 30 min | Advanced | Python | [Lab 11](https://labs.besser-pearl.org/labs/code-generator/) | Extend BESSER |

**You'll learn to**

- Set up an editable BESSER source checkout and run its test suite
- Check what a generator already supports before changing it
- Add a validated attribute to a B-UML metamodel class
- Change a built-in Jinja template so it uses the new concept
- Write a pytest test that fails before the change and passes after it

**You'll need**

- Python 3.11 or 3.12
- Git
- About 1 GB of free disk space for the checkout and its dependencies
- A JDK (javac) for the Java exercise, optional

Online version: https://labs.besser-pearl.org/labs/metamodel-extension/

---

Generators can only use what the metamodel can express. When a project needs a concept B-UML does not have yet, you extend the metamodel and then teach a generator to use it. This is how most contributions to BESSER start.

In this lab you add a maximum length to attributes. In BESSER 8.0.1 every string attribute becomes a `String(100)` column in the SQLAlchemy generator, whether it holds a 13-character ISBN or a long title. You add `max_length` to the `Property` metaclass, use it in the SQLAlchemy template, and protect the change with a test. The exercise then applies the same method to the Java generator.

You work in your own clone of the BESSER repository, in a separate virtual environment, so your normal `pip install besser` setup stays untouched.

### 1. Set up a BESSER source checkout

1. Clone the `development` branch and create a virtual environment inside the clone:

   ```bash
   git clone --branch development https://github.com/BESSER-PEARL/BESSER.git
   cd BESSER
   python -m venv .venv
   source .venv/bin/activate
   ```

   ```powershell
   git clone --branch development https://github.com/BESSER-PEARL/BESSER.git
   cd BESSER
   python -m venv .venv
   .venv\Scripts\Activate.ps1
   ```

2. Install BESSER in editable mode. Python then imports BESSER from your clone, so every change you make to the source takes effect without reinstalling:

   ```bash
   python -m pip install -e .
   ```

3. Check that Python picks up the clone, not a PyPI copy:

   ```bash
   python -c "import besser; print(besser.__file__)"
   ```

   ```text
   /path/to/BESSER/besser/__init__.py
   ```

4. Run the tests for the parts you are going to touch. `pytest` is installed with BESSER's own dependencies:

   ```bash
   python -m pytest tests/BUML/metamodel/structural tests/generators/sqlalchemy tests/generators/java -q
   ```

   ```text
   195 passed in 15.99s
   ```

> **If something goes wrong**
>
> If `besser.__file__` points into `site-packages` instead of your clone, the virtual environment is not active or another BESSER installation shadows it. Activate `.venv` again, and make sure no `PYTHONPATH` variable points at another BESSER folder.

> **Check your work**
>
> `besser.__file__` points into your clone and the three test folders pass. The exact count can differ if `development` has moved on since 8.0.1; what matters is that nothing fails.

### 2. Check what the generators already support

Before you extend anything, find out what is really missing. Earlier versions of this lab asked for unique attributes in SQLAlchemy and for methods in the Java generator. Both exist now. Create a scratch folder outside the clone, for example `../playground/`, and save this as `check_current.py`:

```python
from besser.BUML.metamodel.structural import (
    Class, DomainModel, Property, StringType, IntegerType,
)
from besser.generators.sql_alchemy import SQLAlchemyGenerator

book = Class(name="Book")
book.attributes = {
    Property(name="title", type=StringType),
    Property(name="isbn", type=StringType, is_external_id=True),
    Property(name="pages", type=IntegerType),
}
model = DomainModel(name="Library", types={book})
SQLAlchemyGenerator(model=model, output_dir="output").generate(dbms="sqlite")
```

Run it with `python check_current.py` and look at the `Book` class in `output/sql_alchemy.py`:

```python
class Book(Base):
    __tablename__ = "book"
    id: Mapped_[int] = mapped_column(primary_key=True)
    title: Mapped_[str] = mapped_column(String_(100))
    isbn: Mapped_[str] = mapped_column(String_(100), unique=True)
    pages: Mapped_[int] = mapped_column(Integer_)
```

Two things to notice:

- Uniqueness is covered. `Property` has `is_external_id` for user-facing keys, and the SQLAlchemy and Django generators turn it into `unique=True`.
- Every string is `String_(100)`. The size comes from a fixed `TYPES` mapping in `besser/generators/sql_alchemy/sql_alchemy_generator.py`, and the model has no way to change it:

  ```bash
  python -c "from besser.BUML.metamodel.structural import Property, StringType; Property(name='isbn', type=StringType, max_length=13)"
  ```

  ```text
  TypeError: Property.__init__() got an unexpected keyword argument 'max_length'
  ```

For Java, generating a class with methods shows that the generator writes a stub for each method:

```java
public void searchBook(String title) {
    // TODO: implement searchBook
    throw new UnsupportedOperationException("searchBook is not implemented");
}
```

> **Check your work**
>
> You have seen `unique=True` on `isbn`, `String_(100)` on both string columns, and the `TypeError` for `max_length`. That gap is what you close next.

### 3. Find the Property metaclass

The structural metamodel lives in one file: `besser/BUML/metamodel/structural/structural.py`. Find the class that represents attributes and association ends:

```bash
grep -n "class Property" besser/BUML/metamodel/structural/structural.py
```

```powershell
Select-String -Pattern "class Property" -Path besser\BUML\metamodel\structural\structural.py
```

Both print line 581:

```text
581:class Property(TypedElement):
```

Read how an existing flag is built, for example `is_external_id`. Each concept on a metaclass has four parts, and your new one needs all four:

1. A constructor argument with a default, in `Property.__init__`.
2. A private attribute behind a `@property` getter and a setter. The setter is where the metamodel rejects invalid values: `is_external_id` refuses to be combined with `is_optional`.
3. A line in `__repr__`, so the value shows up when you print a property.
4. An entry in the class docstring, under both `Args` and `Attributes`.

The metaclass is documented on the [structural model page](https://besser.readthedocs.io/en/latest/buml_language/model_types/structural.html).

> **Check your work**
>
> You have found `Property.__init__`, the `is_external_id` getter and setter, and `__repr__` in `structural.py`.

### 4. Add max_length to Property

1. Add the argument at the end of the `__init__` signature. Callers can pass constructor arguments by position, so a new parameter in the middle of the signature would silently shift their values:

   ```python
                    timestamp: datetime = None, metadata: Metadata = None, is_derived: bool = False,
                    uncertainty: float = 0.0, max_length: int = None):

           super().__init__(name, type, timestamp, metadata, visibility, is_derived, uncertainty)
           self.max_length: int = max_length
   ```

2. Add the getter and setter next to `default_value`. `None` means no limit; anything else must be a positive integer:

   ```python
       @property
       def max_length(self) -> int:
           """int: Get the maximum length of the property's value (None means no limit)."""
           return self.__max_length

       @max_length.setter
       def max_length(self, max_length: int):
           """int: Set the maximum length of the property's value.

           Raises:
               ValueError: if max_length is not None and not a positive integer.
           """
           if max_length is not None and (not isinstance(max_length, int) or max_length <= 0):
               raise ValueError("max_length must be a positive integer or None.")
           self.__max_length = max_length
   ```

3. Add `f'max_length={self.max_length}, '` to `__repr__`, after the `default_value` line, and describe `max_length (int)` in the docstring.

4. Try it:

   ```python
   from besser.BUML.metamodel.structural import Property, StringType

   print(Property(name="isbn", type=StringType, max_length=13).max_length)
   print(Property(name="title", type=StringType).max_length)
   try:
       Property(name="bad", type=StringType, max_length=0)
   except ValueError as e:
       print("ValueError:", e)
   ```

   ```text
   13
   None
   ValueError: max_length must be a positive integer or None.
   ```

Because of the editable install, you did not reinstall anything for this to work.

> **Check your work**
>
> A property accepts `max_length=13`, defaults to `None`, and rejects `0` with a `ValueError`.

### 5. Use max_length in the SQLAlchemy template

The SQLAlchemy generator renders each attribute in the `render_attributes` macro of `besser/generators/sql_alchemy/templates/helpers.py.j2`. The column type is picked here:

```jinja
mapped_column({% if attribute.type.name in enumerations|map(attribute='name') %}Enum({{ attribute.type.name }}){% else %}{{types[attribute.type.name]}}{% endif %}
```

`types` is the generator's `TYPES` mapping, where `str` is `String_(100)`. Add a branch for string attributes that have a `max_length`, and keep the mapping as the fallback:

```jinja
mapped_column({% if attribute.type.name in enumerations|map(attribute='name') %}Enum({{ attribute.type.name }}){% elif attribute.type.name == 'str' and attribute.max_length %}String_({{ attribute.max_length }}){% else %}{{types[attribute.type.name]}}{% endif %}
```

Edit only that part of the line; the `Mapped_[...]` part before it stays as it is.

Now generate a model that uses the new concept. In your playground folder, save `max_length_demo.py`:

```python
from besser.BUML.metamodel.structural import (
    Class, DomainModel, Property, StringType, IntegerType,
)
from besser.generators.sql_alchemy import SQLAlchemyGenerator
from besser.generators.sql import SQLGenerator

book = Class(name="Book")
book.attributes = {
    Property(name="title", type=StringType, max_length=255),
    Property(name="isbn", type=StringType, max_length=13, is_external_id=True),
    Property(name="pages", type=IntegerType),
}
model = DomainModel(name="Library", types={book})

SQLAlchemyGenerator(model=model, output_dir="output").generate(dbms="sqlite")
SQLGenerator(model=model, output_dir="output", sql_dialect="sqlite").generate()
```

Run it. `output/sql_alchemy.py` now has the sizes from the model:

```python
class Book(Base):
    __tablename__ = "book"
    id: Mapped_[int] = mapped_column(primary_key=True)
    title: Mapped_[str] = mapped_column(String_(255))
    isbn: Mapped_[str] = mapped_column(String_(13), unique=True)
    pages: Mapped_[int] = mapped_column(Integer_)
```

The SQL generator builds its DDL from the SQLAlchemy code, so `output/tables_sqlite.sql` follows without any change to it:

```sql
CREATE TABLE book (
	id INTEGER NOT NULL, 
	title VARCHAR(255) NOT NULL, 
	isbn VARCHAR(13) NOT NULL, 
	pages INTEGER NOT NULL, 
	PRIMARY KEY (id), 
	UNIQUE (isbn)
)

;
```

> **If something goes wrong**
>
> If the output still shows `String_(100)`, Python is importing another BESSER installation. Run the playground scripts with the `.venv` of your clone active, and check `besser.__file__` again.

> **Check your work**
>
> `title` is `String_(255)`, `isbn` is `String_(13)` and still unique, and the DDL shows `VARCHAR(255)` and `VARCHAR(13)`.

### 6. Write a test for the new concept

BESSER's tests mirror the source tree: generator tests live in `tests/generators/<generator>/`. Create `tests/generators/sqlalchemy/test_max_length.py`:

```python
import os

import pytest

from besser.BUML.metamodel.structural import Class, DomainModel, Property, StringType
from besser.generators.sql_alchemy import SQLAlchemyGenerator

def _book_model(**isbn_kwargs) -> DomainModel:
    book = Class(name="Book")
    book.attributes = {
        Property(name="title", type=StringType),
        Property(name="isbn", type=StringType, **isbn_kwargs),
    }
    return DomainModel(name="Library", types={book})

def _generate(model, tmp_path) -> str:
    SQLAlchemyGenerator(model=model, output_dir=str(tmp_path)).generate(dbms="sqlite")
    with open(os.path.join(tmp_path, "sql_alchemy.py"), encoding="utf-8") as f:
        return f.read()

def test_max_length_defaults_to_none():
    assert Property(name="title", type=StringType).max_length is None

@pytest.mark.parametrize("bad", [0, -5, "13"])
def test_max_length_rejects_invalid_values(bad):
    with pytest.raises(ValueError):
        Property(name="isbn", type=StringType, max_length=bad)

def test_max_length_sets_the_column_size(tmp_path):
    code = _generate(_book_model(max_length=13), tmp_path)
    assert "isbn: Mapped_[str] = mapped_column(String_(13))" in code
    # attributes without max_length keep the generator default
    assert "title: Mapped_[str] = mapped_column(String_(100))" in code
```

`tmp_path` is a pytest fixture that gives each test its own empty folder, so the test never writes into your clone.

Run it:

```bash
python -m pytest tests/generators/sqlalchemy/test_max_length.py -v
```

```text
tests/generators/sqlalchemy/test_max_length.py::test_max_length_defaults_to_none PASSED [ 20%]
tests/generators/sqlalchemy/test_max_length.py::test_max_length_rejects_invalid_values[0] PASSED [ 40%]
tests/generators/sqlalchemy/test_max_length.py::test_max_length_rejects_invalid_values[-5] PASSED [ 60%]
tests/generators/sqlalchemy/test_max_length.py::test_max_length_rejects_invalid_values[13] PASSED [ 80%]
tests/generators/sqlalchemy/test_max_length.py::test_max_length_sets_the_column_size PASSED [100%]

============================== 5 passed in 0.42s ==============================
```

A test that passes proves little until you have seen it fail. Set your two source changes aside, run the test, then bring them back:

```bash
git stash
python -m pytest tests/generators/sqlalchemy/test_max_length.py -q
git stash pop
```

```text
5 failed in 0.55s
```

`git stash` only takes tracked files, so the new test file stays while the metamodel and template changes are set aside.

> **Check your work**
>
> The five tests pass with your changes and all five fail without them.

### 7. Run the regression tests

A metamodel change can break code far from where you made it, such as converters or other generators that build `Property` objects. Run the same three folders as at the start:

```bash
python -m pytest tests/BUML/metamodel/structural tests/generators/sqlalchemy tests/generators/java -q
```

```text
200 passed in 7.10s
```

That is the 195 tests from the start plus your 5. To run the whole suite the way BESSER's CI does, install the web editor backend requirements first; some tests import them. The full run has more than 5000 tests and takes about ten minutes:

```bash
python -m pip install -r besser/utilities/web_modeling_editor/backend/requirements.txt
python -m pytest tests/ -q --ignore=tests/generators/nn
```

> **Note**
>
> `max_length` now exists in Python models only. To use it from the Web Modeling Editor, the JSON converters in `besser/utilities/web_modeling_editor/backend/services/converters/` and the editor's attribute form would also need to carry it. The `is_external_id` flag is a complete example of a property that goes through all those layers: search the source for `is_external_id` and `isExternalId` to see each place. The [contributor guide](https://besser.readthedocs.io/en/latest/contributor_guide.html) describes how to open a pull request.

> **Check your work**
>
> The three folders pass with 5 more tests than at the start, and no existing test fails.

### 8. Exercise: abstract classes in the Java generator

> **Exercise: Generate abstract classes and abstract methods in Java**
>
> The metamodel already has `Class(is_abstract=True)` and `Method(is_abstract=True)`, but the Java generator ignores both. For this model:
>
> ```python
> publication = Class(name="Publication", is_abstract=True)
> publication.attributes = {Property(name="title", type=StringType)}
> publication.methods = {Method(name="price", type=FloatType, is_abstract=True)}
>
> book = Class(name="Book")
> book.attributes = {Property(name="pages", type=IntegerType)}
> model = DomainModel(name="Library", types={publication, book},
>                     generalizations={Generalization(general=publication, specific=book)})
> ```
>
> BESSER 8.0.1 generates `public class Publication {` and a `price()` method with a body that throws. Change the templates in `besser/generators/java_classes/templates/` so that:
>
> - an abstract class is declared `public abstract class Publication {`,
> - an abstract method has no body: `public abstract float price();`,
> - the generated files still compile with `javac *.java`.
>
> Then add a test in `tests/generators/java/` and run the Java tests again.

<details>
<summary>Show a solution</summary>

The class header and the method loop are both in `java_template.py.j2`. Use `class_obj.is_abstract` and `method.is_abstract`. The compile requirement is the hard part: once `price()` is abstract, `Book` no longer compiles because it does not implement it. A concrete class must emit a stub for every abstract method it inherits; `class_obj.all_parents()` gives you the ancestors to collect them from. Look at `tests/generators/java/test_java_generator.py`: it already contains a test that compiles the generated code when `javac` is available, which you can copy.

</details>

> **Exercise: Keep max_length when a model is saved as Python code**
>
> `besser.utilities.domain_model_to_code(model, file_path)` writes a model back out as a B-UML Python script. The web editor uses it for its B-UML export. Right now it drops `max_length`. Make it write `max_length=13` when an attribute has one, and write a round-trip test: build a model, save it, execute the file, and check that the attribute still has `max_length == 13`.

<details>
<summary>Show a solution</summary>

The attribute lines are built in `besser/utilities/buml_code_builder/domain_model_builder.py`, next to the existing `is_external_id_str` variable. There are two places: one for regular classes and one for association classes. Follow the pattern of `is_external_id_str`: an empty string when the value is `None`, otherwise `, max_length=13`.

</details>

---

Checked against BESSER 8.0 on 2026-10-02.
