Configuration¶
The Modeling Agent reads two kinds of configuration:
config.yamlat the repository root — the BESSER Agentic Framework (BAF) settings: NLP, the WebSocket platform, and the server OpenAI key. Copyconfig_example.yamltoconfig.yamland edit the values.Environment variables — everything the agent itself added on top: the per-call-site model routing table, the backend URL, and a handful of behavioral switches. Each one is declared once on
AgentSettingsinsrc/common/settings.py; read the environment only through it.
On this page
config.yaml Reference¶
The configuration file uses YAML format. Below is the full structure with all supported keys.
agent:
check_transitions_delay: 5
nlp:
language: en
region: US
timezone: Europe/Madrid
pre_processing: True
intent_threshold: 0.55
openai:
api_key: your-api-key
platforms:
websocket:
host: localhost
port: 8765
# CORS: browser origins allowed to open a WebSocket to this agent.
origins:
- "https://editor.besser-pearl.org"
- "http://localhost:3000"
- "http://localhost:5173"
- "http://localhost:8080"
streamlit:
host: localhost
port: 5000
Agent¶
Key |
Default |
Description |
|---|---|---|
|
|
Delay (seconds) before checking state transitions |
WebSocket Platform¶
Key |
Default |
Description |
|---|---|---|
|
|
Bind address for the WebSocket server ( |
|
|
Port for the WebSocket server |
|
production hosts + localhost |
CORS whitelist of browser origins. BAF passes this to
|
|
|
Streamlit UI host (the agent runs with |
|
|
Streamlit UI port |
NLP / LLM¶
Key |
Default |
Description |
|---|---|---|
|
|
Language code for NLP processing |
|
|
Region for locale-specific processing |
|
|
Timezone for timestamp handling |
|
|
Enable input pre-processing |
|
|
Minimum confidence for BAF’s local intent classifier. Note this does not gate the unified classifier, which is authoritative — see Intent Recognition. |
|
(required) |
The server OpenAI key. A user’s own key (BYOK) is routed separately per request — see below. |
Model Routing¶
Location: src/llm/model_config.py
Every LLM call in the agent belongs to a tier, and each tier is
independently env-overridable so a deployment (e.g. a gateway exposing
different model names) can re-point one tier without a code change. The
variable name is the tier name prefixed with BESSER_AGENT_MODEL_.
Constant |
Default |
Used by |
|---|---|---|
|
|
The unified classifier, the request planner, JSON repair /
self-correction / name-extraction recovery, the memory summarizer,
UML RAG, help and fallback streaming, and |
|
|
Complete-system generation for class, state machine, object, agent and quantum circuit diagrams, where output quality is the product |
|
|
GUI complete-system generation. Its own knob because design quality tracks the model’s taste far more than diagram generation does. |
|
|
Single-element and modification structured calls,
|
|
|
The free-text design-reasoning pass of two-pass generation |
|
|
File-conversion vision calls (image / PDF → diagram) |
|
|
RAG embeddings. Pinned explicitly so a silent library default bump can never invalidate the persisted vector store. |
Example: point the classifier tier at a different model without touching code:
BESSER_AGENT_MODEL_CLASSIFIER=gpt-4o
BESSER_AGENT_MODEL_GENERATION_LARGE=gpt-5.6-sol
Temperature vs. reasoning_effort¶
The gpt-5 and gpt-6 families and the o-series reject an explicit
temperature other than the default — the API returns HTTP 400. Call
sites must therefore omit the parameter for those models and pass
reasoning_effort instead. They also take only max_completion_tokens
(max_tokens is a 400). Claude generation 5 and later (Opus 5.5,
Opus 5, Sonnet 5, Fable 5 / 5.1), Opus 4.7 / 4.8 and Mythos reject
temperature / top_p / top_k as well; a user’s Anthropic key sends
them an output_config.effort instead. A user’s Anthropic key sends no
sampling parameters to any Claude model: the anthropic SDK removed them
in 1.0, and API version 2026-10-21 rejects them on every model.
model_config holds the rule:
supports_custom_temperature(model) -> bool
# False for gpt-5 and later (gpt-6, ...), o1 / o3 / o4, and the
# Claude models listed above
reasoning_effort_for(model) -> str | None
# None for models that accept a temperature (they reject the param);
# otherwise MODEL_REASONING_EFFORT
sampling_params(model, temperature) -> dict
# {"temperature": t}, {"reasoning_effort": e} or {}
llm/provider.py applies it to every shared-client call (the BYOK client in
llm/byok.py applies it per provider), and app/agent_setup.py to the
BAF constructor parameters. Call sites never pass either parameter themselves.
Variable |
Default |
Description |
|---|---|---|
|
|
|
Environment Variables¶
Location: src/common/settings.py (AgentSettings). Variables
marked at import are read once when their module loads; the others at each
use.
Variable |
Default |
Description |
|---|---|---|
|
— |
Server OpenAI key. The Docker entrypoint writes it into the
generated |
|
|
The two host entries of |
|
unset |
Endpoint of the shared OpenAI client (read by the SDK). The agent reads it to price calls on that route (see Cost and Model Routing). |
|
see above |
Per-tier model overrides (at import; blank means the default) |
|
|
Base URL of the BESSER backend, used by the opt-in study telemetry
collector ( |
|
unset (off) |
Whether a BYOK request may specify its own API base URL. Set to
|
|
unset |
Path to the deployment’s model catalog, the JSON file the BESSER
backend reads too (mount the same file into both; format in BESSER’s
|
|
auto-detect |
Pins speech-to-text to a language ( |
|
|
Use the compact class-diagram spec schema for generation (at
import); only |
|
|
Seconds between the INFO log lines with the token and cost totals
(see Cost and Model Routing). |
|
unset (off) |
Log full LLM prompts ( |
|
|
Set defensively at startup by |
Bring Your Own Key (BYOK)¶
Location: src/llm/byok.py, plus the request boundary in
patches/websocket_platform.py.
A user can paste their own API key in the frontend. It arrives through
user_set_variable (user_api_key, user_api_provider,
user_api_model, user_api_base), stays with the socket that sent it, and
is never written to the BAF session, config.yaml or the shared LLM objects.
Routing is driven by a contextvars.ContextVar (current_byok). The
WebSocket request boundary sets it just before agent.receive_event and
resets it after. Because loop.call_soon_threadsafe copies the calling
thread’s context, the value propagates into that session’s event-loop
thread for that turn only — so two concurrent users can never cross keys,
and the shared server LLM is never mutated.
Property |
Value |
|---|---|
Supported providers |
|
Routed call shapes |
Every |
Images on a key that cannot read them |
Nebius, a catalog gateway and a custom endpoint have no known image-capable model, so image/PDF conversion and a GUI mockup run on the server key (logged as a WARNING). A provider that rejects the image input (an HTTP 400 whose error names the image) gets a “can’t read this image” reply; any other 400 (context length, a bad parameter) gets the generic conversion error. The provider’s reason is logged either way. |
Not routed |
The local BAF fallback classifier (no LLM), BAF’s own RAG and intent-classifier calls, RAG embeddings and speech-to-text |
Per-request timeout |
300 s (without it the SDKs default to several minutes, letting one hung call stall a whole turn; 120 s cut long-spec reasoning passes short) |
Error handling |
Provider call errors (auth, rate limit) propagate so the existing
|
Because BYOK bypasses any gateway, the agent’s per-call tiers are collapsed
into two and mapped to each provider’s equivalent (_PROVIDER_TIER_MODELS
in src/llm/byok.py). A model the user explicitly chose is used for every call;
only without one does small use the provider’s cheap sibling, so small
edits, routing and repair calls stay inexpensive on the user’s key. The
mapping and its cost effect are in Cost and Model Routing.
Cost and Model Routing¶
What a message costs is decided by which call sites it reaches and which tier each one requests. This section is the reference for keeping that cost down without losing output quality.
Calls per turn¶
Counts are for the shared server key and a request that succeeds first time.
Turn type |
LLM calls |
|---|---|
Every user message |
One unified-classifier call ( |
Greeting, help, “what can you do” |
Canned replies cost nothing more. Free-form help and fallback replies
stream one more |
Single element or modification |
One structured call on |
Complete system: class diagram, state machine, GUI |
One structured call ( |
Complete system: object, agent, quantum circuit |
One structured call on |
Complete system: BPMN |
Two calls, both on the |
Complete system: User Profile |
One structured call on the |
Multi-step request |
One extra |
Long conversation |
One |
Reply in a language other than English |
One |
Tiers¶
Routing is by call site: each call names the tier it needs (see
model routing above for the overrides). Prices are USD
per million tokens, from the model catalog (BESSER_MODEL_CATALOG) when it
prices the model on the endpoint the call goes to (a gateway bills its own
rates), else from the vendor price file (see
where prices come from).
Tier |
Default |
Input / cached / output |
Why this tier |
|---|---|---|---|
|
|
0.10 / 0.01 / 0.50 |
Runs on every message with a small, schema-constrained output, so it is the cheapest model that routes reliably. |
|
|
0.25 / 0.025 / 2.00 |
Complete-system diagrams, where output quality is the product. |
|
|
2.00 / 0.20 / 10.00 |
GUI design quality tracks the model’s taste far more than diagram generation does. |
|
|
0.10 / 0.01 / 0.50 |
Single-element and modification calls: latency-sensitive and schema-constrained. |
|
|
0.25 / 0.025 / 2.00 |
The free-text design analysis of two-pass generation. |
|
|
2.50 / 1.25 / 10.00 |
Image and PDF input for file conversion. |
|
|
0.02 / — / — |
RAG vectors; pinned so the persisted store keeps matching. |
gpt-6-sol and gpt-6-luna are not in the price file yet; their cached
rates assume the 10 % that gpt-6-astra lists.
Static prefix first¶
Both providers bill a repeated prompt prefix at the cached rate (OpenAI
caches automatically from 1024 prompt tokens; Anthropic needs a
cache_control marker and caches from 1024 tokens on Sonnet 5 and from 4096
on Haiku 4.5). A cache hit needs the prefix to be byte-identical, so:
put the static instructions (system prompt, JSON schema) first and the per-message content (history, workspace context, the user’s message) last;
never interpolate a timestamp, id or other per-request value into a system prompt.
The unified classifier follows this rule: its ~9k-token system prompt is a
separate system message ahead of the per-message user block. On a user’s
Anthropic key, LLMProvider.parse sends that prompt plus the schema as a
system block with cache_control: {"type": "ephemeral"}; the first
message in a five-minute window writes it at 1.25x the input rate and later
ones read it at 0.1x.
Every prompt lives in src/prompts/ and tests/test_prompt_snapshots.py
pins a hash of each, so a byte that changes by accident fails the suite.
Output caps, reasoning effort and the two-pass gate¶
Output caps (
src/common/agent_config.py):LLM_MAX_TOKENS_LARGE8192 for complete-system schemas,LLM_MAX_TOKENS_SMALL2048 for single-element and modification schemas,LLM_MAX_TOKENS_TEXT4096 for free text, andGUI_COMPLETE_SYSTEM_MAX_TOKENS16384 for multi-page GUI output. The classifier gets 800 tokens on a non-reasoning model and 4000 on a reasoning model, whose hidden reasoning draws on the same budget. A structured call that hits its cap is retried once with an instruction to be concise; a second truncation fails the call instead of falling back to per-element generation.Reasoning effort:
BESSER_AGENT_MODEL_REASONING_EFFORT(low) is sent asreasoning_effortto gpt-5 / gpt-6 / o-series models and asoutput_config.effortto Claude models that take no sampling parameters. Hidden reasoning is billed as output, so raising it raises the cost of every generation call.Two-pass gate: the reasoning pass runs only when the raw user message is at least
_TWO_PASS_MIN_LENGTH(250) characters. The handler must passraw_requesttopredict_two_pass_structured; without it the gate measures the enriched prompt (history plus workspace context), which is almost always longer, so the extra pass runs on trivial requests too. The class diagram and state machine handlers pass it; the BPMN and GUI handlers do not.
Retries¶
Shared server clients:
src/llm/retry.pyis the only transport retry. The SDK’s own retries are turned off (max_retries=0) so they do not nest under it. A 429 or 5xx is tried up toMAX_ATTEMPTS(4) times with 0.6 / 1.2 / 2.4 s backoff (about 5 s of sleep in the worst case, on top of the failed attempts’ own duration).insufficient_quota,invalid_api_keyand other permanent codes fail on the first attempt.Handler retries:
predict_with_retryandpredict_structuredmake at most one more attempt, never for a rate-limit, authentication or bad-request error. A 5xx that outlasts the transport retry can therefore cost up to 8 HTTP requests for one logical call; it was 24 when the SDK retries were nested in.No fan-out on provider errors: a rate-limit, authentication, bad-request or repeated-truncation error reaches the user (for a rate limit on the shared key, the reply offers adding an own API key). It does not trigger the two-pass single-pass fallback or the class diagram’s per-class fallback, which used to repeat the failing call up to 11 more times.
BYOK clients are not wrapped: the SDK default of 2 retries applies, so a 5xx costs at most 3 HTTP requests per attempt and 6 per logical call.
BYOK cost behaviour¶
With a user’s key the user pays for every routed call. Without a chosen model
the tiers map as follows; a chosen model is used for every call. A call with
images (file conversion, a GUI mockup) follows the vision column: “chosen
model” keeps the pick (else the tier model), because every current OpenAI and
Claude chat model reads images; a model name replaces the pick, which may be
text-only (Mistral’s codestral).
Provider |
|
|
|
|---|---|---|---|
|
|
|
chosen model |
|
|
|
chosen model |
|
|
|
|
|
|
same model |
none (server key) |
The tier is read from the model the call site requests, not from whether
that model is a reasoning model. A small edit on an OpenAI key therefore runs
on gpt-6-luna ($0.10 / $0.50) rather than gpt-6-sol ($2 / $10), and on
an Anthropic key on claude-haiku-5-5 ($0.10 / $0.50) rather than
claude-sonnet-5-5 ($2 / $10). BPMN
and User Profile complete-system generation request the classifier tier, so
they map to small.
Where to see spend¶
src/llm/tracking/token_tracker.py accumulates the tokens and estimated cost
of every recorded call for the whole process since it started. Every
BESSER_AGENT_COST_LOG_INTERVAL seconds (600 by default) the next call logs
one INFO line, for example:
[TokenTracker] totals since start: calls=412 prompt=1893120 (cached=1204480) completion=96210 est_cost=$0.8123
Real provider usage is recorded wherever the SDK returns it, cached prompt
tokens are priced at the cached rate, and a truncated call is counted. Only
BAF’s own predict(), which returns no usage, is estimated from text
length. The tracker supports per-session buckets, but no call site passes a
session id, so only the global totals are populated. The figures are
estimates: the provider’s billing dashboard is authoritative.
Where prices come from¶
A call is priced, in order, from:
the deployment’s model catalog, for the endpoint the call goes to;
src/llm/tracking/data/model_prices.json, a copy of the price file BESSER vendors (besser/llm/data/model_prices.json, reduced from litellm’smodel_prices_and_context_window.json), so the agent and the backend price a model the same way;_UNPUBLISHEDinsrc/llm/tracking/token_tracker.py: the few current models the price file does not list yet. A test fails once a refresh lists one, so its row is deleted.
A gateway’s rates, and a new model, belong in the deployment’s model catalog:
an edit there and a restart, no release. Refresh the price file in BESSER and
copy it here in the same change; with BESSER checked out next to this repo
(or at BESSER_CHECKOUT, where CI checks out its development branch),
tests/test_token_tracker.py fails while the two differ. An id that extends a listed id by a gateway
prefix or a snapshot suffix (claude-haiku-4-5-20251001,
us.anthropic.claude-opus-5-5) is priced as that id, unless the file lists
it under its own rate; a different variant such as gpt-6-sol-pro is not.
A model nothing prices is costed at placeholder rates and logged once as a
warning.
Tunable Constants¶
Location: src/common/agent_config.py — values that are not env-driven but
live in one place instead of being scattered across modules.
Constant |
Value |
Description |
|---|---|---|
|
|
Maximum diagram tabs per type in a workspace |
|
|
Hard cap applied at the protocol boundary, so a huge paste cannot reach memory or an LLM prompt untruncated |
|
|
How long a disconnected session survives before the reaper closes it |
|
|
Streaming chunk buffer size in characters |
|
|
Structured vs. free-text temperature (ignored for gpt-5 / o-series) |
|
|
Completion budgets |
|
|
Recent messages fed verbatim each turn. The rolling summary in
|
RAG Configuration¶
Location: agent_setup.init_rag()
Vector store: ChromaDB, persisted in
uml_vector_store/(auto-created)Source documents:
uml_specs/formal-17-12-05.pdf(OMG UML 2.5.1), indexed in a background thread on the first start: about 2,270 chunks, one embedding pass (~460k tokens).uml_vector_store/.indexedmarks a complete index; without it the store is cleared and rebuilt, so an interrupted run never leaves a partial index. A new container rebuilds it unless/app/uml_vector_storeis a volume.Embedding model:
MODEL_EMBEDDINGS(text-embedding-3-small)Chunking:
RecursiveCharacterTextSplitter, chunk size 1000, overlap 100Retrieval:
k=4, with 6 previous messages of contextAnswering model:
MODEL_CLASSIFIERtier
If RAG initialization fails (missing store, missing key, import error), the agent logs a warning and continues without RAG — UML spec queries fall back to LLM-only responses. Until the first index finishes, the store is empty and answers carry no retrieved context.
Research Study Mode¶
Location: src/conversation/telemetry.py, with the label parsed in
src/protocol/adapters.py.
Study mode is an opt-in usage recording for facilitated research sessions. It
is off unless the editor tab was opened with a study link
(?study=<label>; ?pilot=<label> is still accepted for links already
handed out). The editor then adds context.pilotParticipant to every
message. Without that field the agent records nothing.
For a tagged message, the agent posts one prompt event to
{BESSER_BACKEND_URL}/besser_api/telemetry/event containing:
the per-tab session id and the participant label (a short token such as
P3, validated against^[A-Za-z0-9_-]{1,16}$, never a name or email);the message text, truncated to 2000 characters;
what the agent did with it (the reply action, e.g.
assistant_message) and the active diagram type.
The post runs on a short-timeout background thread and every failure is
swallowed, so a reply is never delayed or broken by it. The agent keeps no
copy. The BESSER backend stores the event only when its own switch
(BESSER_TELEMETRY_ENABLED) is on; storage and retention are described in
the BESSER backend documentation. A participant stops the recording by
closing the tab.
Security Notes¶
Never commit real API keys to the repository.
Use
config_example.yamland.env.exampleas templates.config.yamlis listed in.gitignore.The Docker entrypoint (
src/app/container_config.py) prints the generated config for debugging but redacts theapi_keyline, so the key never lands in container logs.A user’s BYOK key lives only with its socket and in the per-request context var; it is never logged or persisted. A context copy can outlast the socket: BAF’s transition timer re-arms inside the last turn’s context, so that copy goes at the session’s next message, or when the reaper closes the session.
In production, use environment variables or secrets management.