Teach the assistant a skill¶
The assistant knows the feature store. It does not know your business rules: what a good fiber is, which table holds the production runs, how a weekly count is made. A skill teaches it one such thing, in code you control.
This page builds two skills on one made-up table, FIBER_RUNS:
- what is a good fiber? A fiber longer than 1 km with no reject code. Where do I find the fiber id, the length and the reject code?
- how many good fibers per day, week or month? Answered with a chart drawn in the database.
Both ship with the package, so you can try them before you write your own.
Which tool for which need¶
| You want the assistant to... | Use |
|---|---|
| understand a word ("a good fiber", "OEE") | the glossary (Documentation > Glossary in the app; see Business dictionary) |
| know what a table or a column means | documentation of the object |
| apply a business rule, know where the data lives and compute something | a skill |
Write the documentation first. A skill that finds its columns by their documented meaning keeps working when a column is renamed.
The parts of a skill¶
A skill is a folder:
<skills folder>/
good_fiber/
SKILL.md # what the classifier reads: name, intent, description, examples
skill.py # node(state) -> dict : the code that answers
good_fiber_plot/
SKILL.md
skill.py
_lib/ # code shared by the skills; a folder starting with _ is not a skill
__init__.py
fiber_rules.py # the rule, written once
SKILL.md starts with a header the classifier reads:
---
name: good_fiber
intent: GOOD_FIBER
description: Use when the user asks what a good fiber is ... NOT for a chart (use GOOD_FIBER_PLOT).
---
intentis a new name in capitals. Questions the classifier gives this intent reach your skill.descriptiondecides the routing. Say when to use the skill and when not to, naming the neighbouring skill. Two skills with overlapping descriptions steal each other's questions.- A
## Classifier Exampleslist gives the classifier sample questions, onequestion -> INTENTper line. Write plain questions. Do not put the names of your own tables or features in them: the examples are shown to the classifier for every store, and a name it has never seen elsewhere gets copied into answers.
skill.py defines node(state). state is a dictionary; state["question"] is what the person typed. Return:
return {"skill_result": {"answer": "text for the person",
"charts": [payload], # optional, from chart_payload(...)
"docs_sources": ["DB.TABLE"]}} # optional: shown as sources
When answer is set, the assistant returns it as is, with no second model call. Answer by code whenever you can: the text is the
same every time and costs nothing.
SKILL.md alone is seen by the classifier and routed nowhere. Without a skill.py that defines node, the Skills tab says
no skill.py in its routed column and the log warns when the assistant starts.
What a skill can call (parse_period, run_sql, llm_json, chart_payload) is described in Plugin skills.
Load it¶
To try the two skills of this page, point it at the folder the package ships:
import tdfs4ds
print(tdfs4ds.examples_path('plugin_skills')) # set TDFS4DS_SKILLS_FOLDER to this path
Set it before the assistant starts, then open Assistant settings > Skills: both skills are listed, routed: yes.
- The Skills tab imports a
SKILL.mdonly. It never accepts askill.py: the app has no control over who reaches its port, and an uploadedskill.pywould run on the server. Copyskill.pyto the folder yourself. Importing is for engineers and administrators; everyone can see the list. - In the Docker deployment the folder belongs to the server and every user of that server shares its skills.
Step 1: document the table¶
The skill finds its columns by meaning. Document them once:
import tdfs4ds
tdfs4ds.set_object_documentation(
"MY_DB", "FIBER_RUNS",
description="One row per fiber produced.",
columns={
"FIBER_ID": "Unique identifier of the fiber.",
"FIBER_LENGTH_M": "Length of the fiber in metres.",
"REJECT_CODE": "Reason the fiber was rejected; empty when the fiber was accepted.",
"PRODUCED_AT": "Production timestamp of the fiber.",
},
refresh_index=False,
)
The skill reads the documented columns of the table (database from TDFS4DS_FIBER_DATABASE, else the feature store's database)
and matches each field by the words of its description (tdfs4ds.genai.deep_tables.resolve_tags: no model, no guess about the
names). A field no description matches keeps its default name, and the answer says which one it used: documented as "..." or
default name.
Example 1: what is a good fiber?¶
The rule is written once, in _lib/fiber_rules.py, and both skills use it:
_lib/fiber_rules.py
"""The "good fiber" rule and where its data lives: no model, one place to change.
Used by the ``good_fiber`` and ``good_fiber_plot`` skills. The data is a table of production runs,
``FIBER_RUNS(FIBER_ID, FIBER_LENGTH_M, REJECT_CODE, PRODUCED_AT)``. Its database is
``TDFS4DS_FIBER_DATABASE`` when set, else the feature store's database.
"""
import os
import re
TABLE_NAME = "FIBER_RUNS"
MIN_LENGTH_M = 1000 # "longer than 1 km"
GOOD_FIBER_SQL = "FIBER_LENGTH_M > 1000 AND REJECT_CODE IS NULL"
# field -> (default column, words describing its meaning in the business dictionary)
FIELDS = {
"fiber_id": ("FIBER_ID", "identifier id of the fiber"),
"fiber_length": ("FIBER_LENGTH_M", "length of the fiber in metres"),
"reject_code": ("REJECT_CODE", "reject code reason rejected defect"),
"produced_at": ("PRODUCED_AT", "production date time timestamp produced"),
}
GRAINS = {"day": ("day", "jour", "daily", "quotidien", "quotidienne", "journalier", "par jour"),
"week": ("week", "semaine", "weekly", "hebdo", "hebdomadaire"),
"month": ("month", "mois", "monthly", "mensuel", "mensuelle")}
DEFAULT_SPAN = {"day": "last 30 days", "week": "last 12 weeks", "month": "last 12 months"}
def database() -> str:
import tdfs4ds
return os.environ.get("TDFS4DS_FIBER_DATABASE") or tdfs4ds.SCHEMA or ""
def grain_of(question: str) -> str:
"""``day``, ``week`` or ``month`` from the question (English or French); ``day`` when it says nothing."""
words = set(re.findall(r"[a-zà-ÿ]+", (question or "").lower()))
text = (question or "").lower()
for grain in ("month", "week", "day"): # the coarser wins: "per week of the month"
for key in GRAINS[grain]:
if (" " in key and key in text) or key in words or key + "s" in words or key + "ly" in words:
return grain
return "day"
def locate_fields(documented=None, *, db=None, table=TABLE_NAME) -> dict:
"""Where the fiber id, the length, the reject code and the production time are.
Reads the documented columns of the table (``documented``: ``{column: description}``, read from
the business dictionary when None) and matches each field by the meaning of its description,
through ``resolve_tags``. A field no description matches keeps its default name.
Returns ``{field: {"column", "description", "how"}}``, ``how`` being ``documented as ...`` or
``default name``, and ``"_table"``: ``{"database", "table"}``.
"""
from tdfs4ds.genai.deep_tables import documented_columns, resolve_tags
db = db or database()
if documented is None:
try:
documented = documented_columns(db, table)
except Exception: # no connection, no dictionary: defaults
documented = {}
found = {"_table": {"database": db, "table": table}}
for field, (default, meaning) in FIELDS.items():
hits = resolve_tags(meaning, documented) if documented else []
if hits:
hit = hits[0]
found[field] = {"column": hit["tag"], "description": hit["description"],
"how": f"documented as \"{hit['description']}\""}
else:
found[field] = {"column": default, "description": documented.get(default, ""),
"how": "default name"}
return found
def good_condition(fields: dict) -> str:
"""The rule written with the located columns."""
return (f"{fields['fiber_length']['column']} > {MIN_LENGTH_M} "
f"AND {fields['reject_code']['column']} IS NULL")
def qualified_table(fields: dict) -> str:
t = fields["_table"]
return f"{t['database']}.{t['table']}" if t["database"] else t["table"]
def naive_utc(moment) -> str:
"""A window bound as ``YYYY-MM-DD HH:MM:SS`` in UTC, for a TIMESTAMP column."""
import datetime as _dt
return moment.astimezone(_dt.timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
def window_sql(fields: dict, period) -> str:
"""The WHERE part bounding the production time by a ``parse_period`` result (end excluded)."""
col = fields["produced_at"]["column"]
parts = []
if period.get("start"):
parts.append(f"{col} >= TIMESTAMP '{naive_utc(period['start'])}'")
if period.get("end"):
parts.append(f"{col} < TIMESTAMP '{naive_utc(period['end'])}'")
return " AND ".join(parts)
def rule_sentence(french: bool) -> str:
if french:
return (f"Une bonne fibre a une longueur superieure a 1 km ({MIN_LENGTH_M} m) et aucun code de rejet.")
return (f"A good fiber is longer than 1 km ({MIN_LENGTH_M} m) and has no reject code.")
def where_lines(fields: dict, french: bool) -> list:
t = qualified_table(fields)
labels = {"fiber_id": "l'identifiant de la fibre" if french else "the fiber id",
"fiber_length": "la longueur (en metres)" if french else "the fiber length (in metres)",
"reject_code": "le code de rejet (vide = accepte)" if french else "the reject code (empty = accepted)"}
lines = []
for field in ("fiber_id", "fiber_length", "reject_code"):
f = fields[field]
note = f["how"] if f["how"] != "default name" else ("nom par defaut" if french else "default name")
lines.append(f"{labels[field]} : `{t}.{f['column']}` ({note})")
return lines
good_fiber/SKILL.md:
---
name: good_fiber
intent: GOOD_FIBER
description: Use when the user asks what a good (or acceptable, or conforming) fiber is, how a fiber is judged good, or where the fiber id, the fiber length or the reject code are stored; also when they ask how many good fibers there were in a period. NOT for a chart of good fibers per day, week or month (use GOOD_FIBER_PLOT) and NOT for the meaning of a feature (use DEFINITION).
---
# Good fiber (example plugin)
Answers, by code and without a model call, what a good fiber is (longer than 1 km and no reject code),
where the fiber id, the fiber length and the reject code are stored, and, when the question names a
period, how many fibers were good in it. The rule and the table live in `_lib/fiber_rules.py`.
## Classifier Examples
- What is a good fiber? -> GOOD_FIBER
- How do we decide that a fiber is good? -> GOOD_FIBER
- Where do I find the fiber length and the reject code? -> GOOD_FIBER
- How many good fibers did we make last week? -> GOOD_FIBER
- Qu'est-ce qu'une bonne fibre ? -> GOOD_FIBER
- Ou trouver l'identifiant de la fibre ? -> GOOD_FIBER
good_fiber/skill.py:
import importlib
from tdfs4ds.plugins import parse_period, run_sql
from _lib import fiber_rules as rules
def _french(question):
# the agent's own detector, imported as a module (tdfs4ds.agent rebinds the name to a function)
return importlib.import_module("tdfs4ds.agent.consumer_agent")._question_is_french(question)
def node(state):
question = state.get("question") or ""
fr = _french(question)
fields = rules.locate_fields() # by the documented meaning, else the default names
table = rules.qualified_table(fields)
if fr:
lines = [rules.rule_sentence(True), "", "Ou trouver les donnees :"]
else:
lines = [rules.rule_sentence(False), "", "Where to find the data:"]
lines += [f"- {line}" for line in rules.where_lines(fields, fr)]
period = parse_period(question, "UTC") # only when the question names a period
if period is not None:
where = rules.window_sql(fields, period)
good = rules.good_condition(fields)
rows = run_sql(f"SELECT COUNT(*) AS ALL_N, "
f"SUM(CASE WHEN {good} THEN 1 ELSE 0 END) AS GOOD_N FROM {table}"
+ (f" WHERE {where}" if where else ""))
total, good_n = int(rows["ALL_N"][0] or 0), int(rows["GOOD_N"][0] or 0)
first, last = period["start"], period["end"]
span = f"{first:%Y-%m-%d} -> {last:%Y-%m-%d}" if first else f"-> {last:%Y-%m-%d}"
lines += ["", (f"Sur la periode {span} : {good_n} bonnes fibres sur {total}." if fr
else f"In the period {span}: {good_n} good fibers out of {total}.")]
return {"skill_result": {"answer": "\n".join(lines), "docs_sources": [table]}}
Ask "What is a good fiber?", then "How many good fibers did we make last week?". The answer states the rule in plain words,
says where the fiber id, the fiber length and the reject code are (DB.FIBER_RUNS.FIBER_LENGTH_M and so on, with how each was
found) and, when the question names a period, counts the good fibers against all fibers. There is no model call.
Example 2: teach a chart¶
good_fiber_plot/SKILL.md:
---
name: good_fiber_plot
intent: GOOD_FIBER_PLOT
description: Use when the user asks for a chart, a plot or a curve of the number of good fibers per day, per week or per month (optionally over a period such as the last 8 weeks). The chart is drawn in the database. NOT for the definition of a good fiber (use GOOD_FIBER) and NOT for a chart of a feature or a dataset (use PLOT).
---
# Good fibers per day, week or month (example plugin)
Counts the good fibers (the rule of `_lib/fiber_rules.py`) per day, week or month and draws the bars
in the database. The grain comes from the question (day by default); without a period the chart covers
the last 30 days, 12 weeks or 12 months, and the answer says so.
## Classifier Examples
- Plot the number of good fibers per week -> GOOD_FIBER_PLOT
- Show me good fibers per day for the last 14 days -> GOOD_FIBER_PLOT
- Chart of good fibers by month -> GOOD_FIBER_PLOT
- Trace le nombre de bonnes fibres par semaine -> GOOD_FIBER_PLOT
- Graphique des bonnes fibres par mois sur les 6 derniers mois -> GOOD_FIBER_PLOT
good_fiber_plot/skill.py:
import importlib
from tdfs4ds import plotting
from tdfs4ds.plugins import chart_payload, parse_period, run_sql
from _lib import fiber_rules as rules
def _french(question):
return importlib.import_module("tdfs4ds.agent.consumer_agent")._question_is_french(question)
def staging_sql(fields, grain, period):
"""One row per bucket: its first day and the number of good fibers in it."""
produced = rules.window_sql(fields, period)
where = " AND ".join(p for p in (rules.good_condition(fields), produced) if p)
bucket = plotting.period_expression(fields["produced_at"]["column"], grain)
return (f"SELECT {bucket} AS PERIOD_START, CAST(COUNT(*) AS FLOAT) AS PERIOD_VALUE "
f"FROM {rules.qualified_table(fields)} WHERE {where} GROUP BY 1")
def node(state):
question = state.get("question") or ""
fr = _french(question)
grain = rules.grain_of(question)
period = parse_period(question, "UTC")
stated = "" if period else (rules.DEFAULT_SPAN[grain])
if period is None: # no period named: a default one, said in the answer
period = parse_period(stated, "UTC")
fields = rules.locate_fields()
source = staging_sql(fields, grain, period)
panel = plotting.panel(source, "PERIOD_START", "PERIOD_VALUE", kind="bar", x_is_time=True,
title=f"Good fibers per {grain}", xlabel=f"{grain} starting",
ylabel="Good fibers")
result = plotting.plot_panels([panel])
if not result.get("ok"):
return {"skill_result": {"answer": f"{result.get('error') or 'The chart could not be drawn.'}",
"charts": [], "docs_sources": [rules.qualified_table(fields)]}}
total = run_sql(f"SELECT CAST(SUM(PERIOD_VALUE) AS INTEGER) AS N FROM ({source}) t")["N"][0]
first, last = period["start"], period["end"]
span = f"{first:%Y-%m-%d} -> {last:%Y-%m-%d}" if first else f"-> {last:%Y-%m-%d}"
note = (" (periode par defaut : " if fr else " (default period: ") + stated + ")" if stated else ""
if fr:
answer = [f"- Compte : bonnes fibres ({rules.rule_sentence(True)})",
f"- Pas : {grain}", f"- Periode : {span}{note}", f"- Total : {int(total or 0)}"]
else:
answer = [f"- Counted: good fibers ({rules.rule_sentence(False)})",
f"- Grain: {grain}", f"- Period: {span}{note}", f"- Total: {int(total or 0)}"]
return {"skill_result": {"answer": "\n".join(answer), "charts": [chart_payload(result)],
"docs_sources": [rules.qualified_table(fields)]}}
Ask "Plot the number of good fibers per week". The skill:
- reads the grain in the question (day, week or month, in English or French; day by default);
- reads the period (
parse_period), or takes the last 30 days, 12 weeks or 12 months and says so in the answer; - writes one
SELECTthat counts the good fibers per bucket with the shared rule; - draws it in the database with
tdfs4ds.plotting.panel(...)andplot_panels([...])(TD_PLOT), and returns it withchart_payload.
The answer is short bullets: what was counted, the grain, the period, the total.
Test it¶
- In the chat: ask the questions above and read the trace panel: the intent must be
GOOD_FIBERorGOOD_FIBER_PLOT. If another skill answers, sharpen thedescriptionof both. - Offline: the package tests build the real graph with the classifier, the database and the model stubbed, as
tests/test_build_a_skill_examples.pydoes for these two skills. Do the same for yours before you rely on it.
Good practice¶
- Answer by code when the answer is a rule and a count. Use
llm_jsononly to read something the question leaves loose. - One shared rule. The definition of "good" lives in
_lib, so the definition skill and the chart skill cannot disagree. - Never filter a stored feature value from a skill. Read, count, compare; the feature store does not rewrite values and a skill should not either.
- Read with care. Prefer a window and an aggregate over a full scan;
EXPLAINa new query on the real table before you ship it. - Say what you assumed: the default period, the column that was found by name.