Read the news again with an optional language model, capped and schema-bound (refs #58)
ci / test (postgres) (push) Successful in 3m33s
ci / test (sqlite) (push) Successful in 4m16s
ci / image (push) Successful in 2m55s
ci / test (postgres) (pull_request) Successful in 3m42s
ci / test (sqlite) (pull_request) Successful in 4m36s
ci / image (pull_request) Successful in 2m2s

The analyst of SPEC 10.2 point 5 sends the fresh stories about held and
candidate instruments to Anthropic, an OpenAI-compatible service or Ollama,
eight to a request, over plain HTTP with no SDK. The news text travels as
escaped JSON data; only the appendix B schema is kept, instruments not
already linked are dropped, and a verdict can only add a restriction.
Each request goes out only if its worst-case cost still fits under the
daily cap; verdicts are cached by content hash. Without a key nothing is
asked and the rules work as before. ADR 0014 point 15.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-28 12:41:39 +01:00
1 parent 4449ec7a0a
commit dcebfb61e1
20 files changed
+1774 -79

No files matched your search

+1
View File
@@ -646,6 +646,7 @@ legend { display: flex; align-items: center; gap: 10px; font-size: 17px; font-we
.tag-strong { color: var(--text); font-weight: 600; }
.tag-outline { background: none; border: 1px solid var(--control); color: var(--text); font-weight: 400; }
.panel h3.news-title { margin: 0; font-size: 16px; line-height: 22px; font-weight: 600; }
.news-summary { margin: 0; color: var(--text-2); font-size: 14px; line-height: 20px; }
.news-facts { display: flex; align-items: center; flex-wrap: wrap; gap: 6px 24px; margin: 0; color: var(--text-2); font-size: 13.5px; }
.tone { display: inline-flex; align-items: center; gap: 8px; }
.tone .tone-text { color: var(--text-2); }
@@ -381,18 +381,15 @@
}
<h3>Modello linguistico</h3>
<p class="hint">Facoltativo. Rilegge solo le notizie sulle tue posizioni e sugli strumenti candidati: può aggiungere una restrizione, mai toglierla, e non vede né chiavi né conti. Senza modello tutto funziona lo stesso con il classificatore locale. La rilettura non è ancora attiva: chiave e tetto restano pronti per quando lo sarà.</p>
<p class="hint">Facoltativo. Rilegge le notizie delle ultime 24 ore sulle tue posizioni e sugli strumenti candidati, otto per richiesta: può aggiungere una restrizione, mai toglierla, e non vede né chiavi né conti. Senza chiave tutto funziona lo stesso con il classificatore locale. Con Ollama, sul tuo computer o nella tua rete, la chiave non serve.</p>
@DataKey(Anubis.News.NewsModelSettings.KeySecret, "Chiave del modello linguistico")
<form method="post" action="/azioni/impostazioni/@_llmCap.Key" class="form-inline">
<AntiforgeryToken />
<input type="hidden" name="ritorno" value="/impostazioni#notizie" />
<label for="tetto">Tetto di spesa al giorno (€)</label>
<input id="tetto" name="valore" inputmode="decimal" autocomplete="off" value="@Format.Number(decimal.Parse(_llmCap.Value, CultureInfo.InvariantCulture), 2)" readonly="@(_llmCap.ReadOnly || Shell.IsDemo)" required />
@if (!_llmCap.ReadOnly && !Shell.IsDemo)
{
<button class="btn btn-small" type="submit">Salva</button>
}
</form>
@ModelSetting(Anubis.News.NewsModelSettings.Provider.Key, "servizio", "Servizio", null)
@ModelSetting(Anubis.News.NewsModelSettings.Model.Key, "modello", "Modello", null)
@ModelSetting(Anubis.News.NewsModelSettings.Address.Key, "indirizzo", "Indirizzo (vuoto per quello solito del servizio)", null)
@ModelSetting(Anubis.News.NewsModelSettings.PriceIn.Key, "prezzo-letti", "Dollari per milione di token letti", 4)
@ModelSetting(Anubis.News.NewsModelSettings.PriceOut.Key, "prezzo-scritti", "Dollari per milione di token scritti", 4)
@ModelSetting(Anubis.News.NewsModelSettings.DailyCap.Key, "tetto", "Tetto di spesa al giorno (€)", 2)
<p class="note">I prezzi in dollari li conto come euro: la spesa calcolata è un po' più alta di quella vera, mai più bassa. Il tetto vale da mezzanotte a mezzanotte; prima di ogni richiesta controllo che anche il caso peggiore ci stia dentro.</p>
<h3>Calendario</h3>
<p class="hint">Senza chiave di Finnhub non conosco le date delle trimestrali e la mean reversion non usa il suo filtro; senza chiave di FRED il calendario usa solo Forex Factory. Le chiavi sono gratuite.</p>
@@ -539,7 +536,7 @@
private SettingValue _meetings = new(SettingsStore.CentralBankMeetings.Key, "", false, null);
private readonly List<SettingValue> _newsRules = [];
private SettingValue _llmCap = new(Anubis.News.NewsModelSettings.DailyCap.Key, "0.50", false, null);
private readonly Dictionary<string, SettingValue> _llm = [];
private IReadOnlyList<Anubis.News.NewsSource> _newsSources = [];
private readonly Dictionary<string, SecretStatus> _dataKeys = [];
private List<SettingChange> _history = [];
@@ -576,7 +573,10 @@
_newsRules.Add(await services.Settings.GetAsync(rule.Key, ct));
}
_llmCap = await services.Settings.GetAsync(Anubis.News.NewsModelSettings.DailyCap.Key, ct);
foreach (var setting in Anubis.News.NewsModelSettings.All)
{
_llm[setting.Key] = await services.Settings.GetAsync(setting.Key, ct);
}
_newsSources = await new Anubis.News.NewsStore(services.Db, Clock).ListSourcesAsync(ct);
foreach (var name in Forms.DataKeys)
{
@@ -657,11 +657,62 @@
"chiave" => "La chiave è vuota o contiene spazi: copiala di nuovo così come la dà il servizio.",
"chiave-ambiente" => "Questa chiave arriva dalle variabili d'ambiente: si cambia nella configurazione del container.",
"tetto" => $"Il tetto di spesa va scritto in euro, da 0 a {Anubis.News.NewsModelSettings.MaxCap:0}, per esempio 0,50.",
"modello" => "Valore non valido per il modello linguistico: il nome come lo dà il servizio, un indirizzo https:// (http:// solo nella tua rete), prezzi da 0 a 200.",
_ => PasswordMessages.For(Errore),
};
// A key of SPEC 13.5 that is not a broker's: its state, a field to replace it, a button to take it away. Never the value.
// One setting of the language model: a choice for the service, a field for the others; amounts shown in Italian.
private RenderFragment ModelSetting(string key, string id, string label, int? decimals)
{
var definition = SettingsStore.Definition(key);
var value = _llm.GetValueOrDefault(key) ?? new SettingValue(key, definition.Default, false, null);
var locked = value.ReadOnly || Shell.IsDemo;
var shown = decimals is { } d ? Format.Number(decimal.Parse(value.Value, CultureInfo.InvariantCulture), d) : value.Value;
var provider = _llm.GetValueOrDefault(Anubis.News.NewsModelSettings.Provider.Key)?.Value ?? Anubis.News.NewsModelProviders.Anthropic;
return @<form method="post" action="/azioni/impostazioni/@key" class="form-inline">
<AntiforgeryToken />
<input type="hidden" name="ritorno" value="/impostazioni#notizie" />
<label for="@id">@label</label>
@if (definition.Allowed is { } choices)
{
<select id="@id" name="valore" disabled="@locked" data-autosubmit>
@foreach (var choice in choices)
{
<option value="@choice" selected="@(choice == value.Value)">@ProviderName(choice)</option>
}
</select>
@if (!locked)
{
<noscript><button class="btn btn-small" type="submit">Salva</button></noscript>
}
}
else
{
<input id="@id" name="valore" inputmode="@(decimals is null ? "text" : "decimal")" autocomplete="off" spellcheck="false" value="@shown"
placeholder="@(key == Anubis.News.NewsModelSettings.Address.Key ? Anubis.News.NewsModelProviders.DefaultAddress(provider).ToString() : null)"
readonly="@locked" required="@(key != Anubis.News.NewsModelSettings.Address.Key)" />
@if (!locked)
{
<button class="btn btn-small" type="submit">Salva</button>
}
}
@if (value.ReadOnly)
{
<span class="hint">Fissato da @value.Source: si cambia lì.</span>
}
</form>;
}
private static string ProviderName(string provider) => provider switch
{
Anubis.News.NewsModelProviders.Anthropic => "Anthropic (Claude)",
Anubis.News.NewsModelProviders.OpenAi => "Compatibile con OpenAI",
Anubis.News.NewsModelProviders.Ollama => "Ollama, sul tuo computer o in rete",
_ => provider,
};
private RenderFragment DataKey(string name, string label)
{
var status = _dataKeys.GetValueOrDefault(name) ?? new SecretStatus(name, false, false, null);
@@ -48,6 +48,10 @@
}
</p>
<h3 class="news-title">@n.Title</h3>
@if (n.Summary is { } summary)
{
<p class="news-summary"><span class="sr-only">Riassunto del modello linguistico: </span>@summary</p>
}
<p class="news-facts">
<span class="tone @(n.Direction < 0 ? "loss" : n.Direction > 0 ? "gain" : null)">
@if (n.Direction == 0)
+15 -9
View File
@@ -238,28 +238,34 @@ internal static partial class Forms
{
var back = Back(form, "/impostazioni");
var news = Anubis.News.NewsRuleSettings.All.Any(d => d.Key == key);
var cap = key == Anubis.News.NewsModelSettings.DailyCap.Key;
var model = Anubis.News.NewsModelSettings.All.Any(d => d.Key == key);
if (key != SettingsStore.Theme.Key && key != SettingsStore.Currency.Key && key != SettingsStore.CentralBankMeetings.Key && key != SettingsStore.TelegramStatus.Key &&
!news && !cap)
!news && !model)
{
return Results.Redirect(With(back, "errore", "impostazione"));
}
if ((news || cap) && host.IsDemo)
if ((news || model) && host.IsDemo)
{
return Results.Redirect(With(back, "errore", "motore"));
}
if (cap)
if (model)
{
// "0,50" as the user writes it; stored as "0.50".
var amount = form["valore"].ToString().Trim().Replace("€", "", StringComparison.Ordinal).Trim().Replace(',', '.');
if (Anubis.News.NewsModelSettings.CheckCap(amount) is not null)
// Amounts as the user writes them, "0,50" or "0,50 €", stored as "0.50"; the other values trimmed.
var value = form["valore"].ToString().Trim();
if (Anubis.News.NewsModelSettings.IsAmount(key))
{
return Results.Redirect(With(back, "errore", "tetto"));
value = Anubis.News.NewsModelSettings.Amount(value)?.ToString(System.Globalization.CultureInfo.InvariantCulture) ?? value;
}
var saved = await Endpoints.SetSettingAsync(host, key, amount, context, ct).ConfigureAwait(false);
var definition = SettingsStore.Definition(key);
if ((definition.Check?.Invoke(value) is not null) || (definition.Allowed is { } allowed && !allowed.Contains(value, StringComparer.Ordinal)))
{
return Results.Redirect(With(back, "errore", key == Anubis.News.NewsModelSettings.DailyCap.Key ? "tetto" : "modello"));
}
var saved = await Endpoints.SetSettingAsync(host, key, value, context, ct).ConfigureAwait(false);
return Results.Redirect(saved is IStatusCodeHttpResult { StatusCode: StatusCodes.Status204NoContent } ? back : With(back, "errore", "impostazione"));
}
+24 -3
View File
@@ -72,9 +72,30 @@ internal sealed record NewsView(
}
var (rows, collecting) = await SourcesAsync(services, shell, clock, cancellationToken).ConfigureAwait(false);
return new NewsView(board, mood, calendar, rows,
"Tutte le notizie passano da un modello locale, gratuito, sul tuo computer. La rilettura con un modello linguistico non è ancora attiva: oggi non è costato nulla.",
collecting);
// Only reads what was spent: the screen never asks the model anything.
var model = await new NewsAnalyst(services.Db, clock, services.Settings, services.Secrets.RevealAsync,
(_, _) => throw new InvalidOperationException("La schermata non interroga il modello.")).SpendingAsync(cancellationToken).ConfigureAwait(false);
return new NewsView(board, mood, calendar, rows, SpendingText(model), collecting);
}
/// <summary>The spending of the day in words (SPEC 13.6): what the language model read and what it cost, against the cap.</summary>
public static string SpendingText(ModelSpending model)
{
ArgumentNullException.ThrowIfNull(model);
const string Local = "Tutte le notizie passano da un modello locale, gratuito, sul tuo computer.";
if (!model.Configured)
{
return Local + " Il modello linguistico non è configurato: oggi non è costato nulla.";
}
var read = model.Judged switch
{
0 => "Oggi il modello linguistico non ha ancora riletto nessuna notizia",
1 => "Oggi il modello linguistico ha riletto 1 notizia sulle tue posizioni e sugli strumenti candidati",
var n => $"Oggi il modello linguistico ha riletto {n} notizie sulle tue posizioni e sugli strumenti candidati",
};
var full = model.Spent >= model.Cap ? " Il tetto è raggiunto: fino a mezzanotte giudica solo il modello locale." : "";
return $"{Local} {read}: è costato {Format.Money(model.Spent)} su un tetto di {Format.Money(model.Cap)}.{full}";
}
private static async Task<IReadOnlyList<MoodGauge>> MoodAsync(MoodStore store, DateTimeOffset now, CancellationToken cancellationToken)