The independent review of phase 7 found that an answer with half a Unicode character, or of an unexpected shape, escaped the validation as an exception: its cost was lost, it was paid again every two minutes past the daily cap, and the diary of the news stopped. The same happened to the whole round with an article cut in the middle of an emoji. Such answers are now refused like any other, the cost is written before the request leaves and settled with what the service used, never clamped to the estimate, and neither the analyst nor one source can stop the others. The estimate counts every byte as a token, so it is a true worst case. Summaries with bare domains or invisible characters are refused. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
ae4ae4ed92
commit
61878c2023
7 files changed
+353
-40
No files matched your search
@@ -1,5 +1,6 @@
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Xml;
|
||||
using System.Xml.Linq;
|
||||
@@ -119,13 +120,45 @@ public static partial class FeedParser
|
||||
}
|
||||
|
||||
var text = WebUtility.HtmlDecode(Tags().Replace(WebUtility.HtmlDecode(Tags().Replace(html, " ")), " "));
|
||||
text = Spaces().Replace(text, " ").Trim();
|
||||
text = Spaces().Replace(Printable(text), " ").Trim();
|
||||
if (text.Length == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return text.Length <= max ? text : text[..(max - 1)].TrimEnd() + "…";
|
||||
return Cut(text, max);
|
||||
}
|
||||
|
||||
/// <summary>At most <paramref name="max"/> characters, never ending with half an emoji: half a character cannot be stored.</summary>
|
||||
public static string Cut(string text, int max)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(text);
|
||||
if (text.Length <= max)
|
||||
{
|
||||
return text;
|
||||
}
|
||||
|
||||
var end = max - 1;
|
||||
return text[..(char.IsHighSurrogate(text[end - 1]) ? end - 1 : end)].TrimEnd() + "…";
|
||||
}
|
||||
|
||||
// Control characters (PostgreSQL refuses the zero) and halves of characters become spaces.
|
||||
private static string Printable(string text)
|
||||
{
|
||||
var clean = new StringBuilder(text.Length);
|
||||
for (var i = 0; i < text.Length; i++)
|
||||
{
|
||||
if (char.IsHighSurrogate(text[i]) && i + 1 < text.Length && char.IsLowSurrogate(text[i + 1]))
|
||||
{
|
||||
clean.Append(text[i]).Append(text[++i]);
|
||||
}
|
||||
else
|
||||
{
|
||||
clean.Append(char.IsSurrogate(text[i]) || char.IsControl(text[i]) ? ' ' : text[i]);
|
||||
}
|
||||
}
|
||||
|
||||
return clean.ToString();
|
||||
}
|
||||
|
||||
private static string? Language(string? code) =>
|
||||
|
||||
@@ -49,11 +49,7 @@ public sealed class LanguageModel(HttpClient http, NewsModelConfig config, strin
|
||||
}
|
||||
|
||||
var body = await ReadLimitedAsync(response.Content, timeout.Token).ConfigureAwait(false);
|
||||
return config.Provider == NewsModelProviders.Anthropic ? ReadAnthropic(body) : ReadOpenAi(body);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return new ModelReply(null, 0, 0, "risposta del servizio illeggibile", Billed: true);
|
||||
return Read(body);
|
||||
}
|
||||
catch (Exception ex) when (ex is HttpRequestException or IOException or FormatException || (ex is OperationCanceledException && !cancellationToken.IsCancellationRequested))
|
||||
{
|
||||
@@ -62,6 +58,19 @@ public sealed class LanguageModel(HttpClient http, NewsModelConfig config, strin
|
||||
}
|
||||
}
|
||||
|
||||
// Whatever the service sent back, of any shape: what does not fit is an answer that cannot be used, never an exception.
|
||||
private ModelReply Read(string body)
|
||||
{
|
||||
try
|
||||
{
|
||||
return config.Provider == NewsModelProviders.Anthropic ? ReadAnthropic(body) : ReadOpenAi(body);
|
||||
}
|
||||
catch (Exception ex) when (ex is JsonException or InvalidOperationException)
|
||||
{
|
||||
return new ModelReply(null, 0, 0, "risposta del servizio illeggibile", Billed: true);
|
||||
}
|
||||
}
|
||||
|
||||
private HttpRequestMessage Anthropic(ModelRequest request)
|
||||
{
|
||||
var body = new JsonObject
|
||||
|
||||
@@ -69,17 +69,20 @@ public sealed partial class NewsAnalyst(Database db, IClock clock, SettingsStore
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The most a request can cost: every character read counted as half a token (real text takes three or four
|
||||
/// characters a token) and every token it may write. Asked only while this still fits under the cap, so the cap
|
||||
/// holds even if the service bills the worst case.
|
||||
/// The most a request can cost: every byte read counted as a token (a token is one byte or more; real text takes
|
||||
/// three or four characters), a margin for what the service adds, and every token it may write. Asked only while
|
||||
/// this still fits under the cap.
|
||||
/// </summary>
|
||||
public static decimal Estimate(NewsModelConfig config, ModelRequest request)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
var characters = request.Instructions.Length + request.Message.Length + request.Schema.ToJsonString().Length;
|
||||
return Cost(config, (characters / 2) + 1, request.MaxOutput);
|
||||
var bytes = Encoding.UTF8.GetByteCount(request.Instructions) + Encoding.UTF8.GetByteCount(request.Message) + Encoding.UTF8.GetByteCount(request.Schema.ToJsonString());
|
||||
return Cost(config, bytes + ServiceMargin, request.MaxOutput);
|
||||
}
|
||||
|
||||
// Tokens a service may add around the request: the turns, its own words about the schema.
|
||||
private const int ServiceMargin = 1000;
|
||||
|
||||
/// <summary>The room for the answer: thinking included, eight verdicts fit with margin.</summary>
|
||||
public static int MaxOutput(int items) => 2000 + (400 * items);
|
||||
|
||||
@@ -137,14 +140,32 @@ public sealed partial class NewsAnalyst(Database db, IClock clock, SettingsStore
|
||||
return new AnalystRound(calls, judged, cached.Count, spentNow, "tetto di spesa raggiunto");
|
||||
}
|
||||
|
||||
var reply = await model.AskAsync(request, cancellationToken).ConfigureAwait(false);
|
||||
// Counted before it leaves, settled after: a stop of the bot or a fault in between cannot lose the cost.
|
||||
var call = await ReserveAsync(config, batch.Sum(g => g.Count), estimate, cancellationToken).ConfigureAwait(false);
|
||||
ModelReply reply;
|
||||
try
|
||||
{
|
||||
reply = await model.AskAsync(request, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
LogUnforeseen(_logger, ex);
|
||||
reply = new ModelReply(null, 0, 0, "errore imprevisto", Billed: true);
|
||||
}
|
||||
|
||||
// What the service says it used, even above the estimate: the cap is compared with the real spending.
|
||||
var known = reply.InputTokens > 0 || reply.OutputTokens > 0;
|
||||
var cost = !reply.Billed ? 0m : known ? Math.Min(Cost(config, reply.InputTokens, reply.OutputTokens), estimate) : estimate;
|
||||
var cost = !reply.Billed ? 0m : known ? Cost(config, reply.InputTokens, reply.OutputTokens) : estimate;
|
||||
if (cost > estimate)
|
||||
{
|
||||
LogAbove(_logger, config.Provider, cost, estimate);
|
||||
}
|
||||
|
||||
// Without any answer the stories are asked again later; an answer out of the schema is final, it is not paid twice.
|
||||
var lost = reply.Text is null && !known;
|
||||
var outcomes = reply.Text is null ? [.. items.Select(i => new VerdictOutcome(i.Item, null, reply.Problem ?? "risposta senza testo"))]
|
||||
: NewsVerdicts.Parse(reply.Text, items);
|
||||
await StoreAsync(config, batch, outcomes, reply, cost, lost, cancellationToken).ConfigureAwait(false);
|
||||
await StoreAsync(call, batch, outcomes, reply, cost, lost, cancellationToken).ConfigureAwait(false);
|
||||
calls++;
|
||||
spentNow += cost;
|
||||
if (lost)
|
||||
@@ -214,7 +235,7 @@ public sealed partial class NewsAnalyst(Database db, IClock clock, SettingsStore
|
||||
return [.. result.Take(BatchSize * MaxCallsPerRound)];
|
||||
}
|
||||
|
||||
private static string Cut(string text, int length) => text.Length <= length ? text : text[..(length - 1)] + "…";
|
||||
private static string Cut(string text, int length) => FeedParser.Cut(text, length);
|
||||
|
||||
// Stories whose very question was already answered take that verdict at no cost.
|
||||
private Task<HashSet<Guid>> FromCacheAsync(IReadOnlyList<Candidate> candidates, CancellationToken cancellationToken) =>
|
||||
@@ -235,18 +256,26 @@ public sealed partial class NewsAnalyst(Database db, IClock clock, SettingsStore
|
||||
return hit;
|
||||
}, cancellationToken);
|
||||
|
||||
private Task<int> StoreAsync(NewsModelConfig config, IReadOnlyList<List<Candidate>> batch, IReadOnlyList<VerdictOutcome> outcomes, ModelReply reply, decimal cost, bool lost,
|
||||
private Task<Guid> ReserveAsync(NewsModelConfig config, int stories, decimal estimate, CancellationToken cancellationToken) =>
|
||||
db.WriteAsync(async s =>
|
||||
{
|
||||
var call = Ids.NewId(clock);
|
||||
await s.ExecuteAsync(
|
||||
"INSERT INTO news_model_calls (id, provider, model, stories, input_tokens, output_tokens, cost, problem, created_at) " +
|
||||
"VALUES (@id, @p, @m, @n, 0, 0, @c, 'senza risposta', @now)",
|
||||
cancellationToken, ("id", call), ("p", config.Provider), ("m", config.Model), ("n", (long)stories), ("c", estimate), ("now", clock.UtcNow)).ConfigureAwait(false);
|
||||
return call;
|
||||
}, cancellationToken);
|
||||
|
||||
private Task<int> StoreAsync(Guid call, IReadOnlyList<List<Candidate>> batch, IReadOnlyList<VerdictOutcome> outcomes, ModelReply reply, decimal cost, bool lost,
|
||||
CancellationToken cancellationToken) =>
|
||||
db.WriteAsync(async s =>
|
||||
{
|
||||
var now = clock.UtcNow;
|
||||
var call = Ids.NewId(clock);
|
||||
var problems = outcomes.Where(o => o.Problem is not null).Select(o => o.Problem).Distinct().ToList();
|
||||
await s.ExecuteAsync(
|
||||
"INSERT INTO news_model_calls (id, provider, model, stories, input_tokens, output_tokens, cost, problem, created_at) " +
|
||||
"VALUES (@id, @p, @m, @n, @in, @out, @c, @pr, @now)",
|
||||
cancellationToken, ("id", call), ("p", config.Provider), ("m", config.Model), ("n", (long)batch.Sum(g => g.Count)), ("in", reply.InputTokens),
|
||||
("out", reply.OutputTokens), ("c", cost), ("pr", problems.Count == 0 ? null : string.Join("; ", problems)), ("now", now)).ConfigureAwait(false);
|
||||
await s.ExecuteAsync("UPDATE news_model_calls SET input_tokens = @in, output_tokens = @out, cost = @c, problem = @pr WHERE id = @id", cancellationToken,
|
||||
("id", call), ("in", reply.InputTokens), ("out", reply.OutputTokens), ("c", cost),
|
||||
("pr", problems.Count == 0 ? null : string.Join("; ", problems))).ConfigureAwait(false);
|
||||
if (lost)
|
||||
{
|
||||
return 0;
|
||||
@@ -305,6 +334,12 @@ public sealed partial class NewsAnalyst(Database db, IClock clock, SettingsStore
|
||||
[LoggerMessage(Level = LogLevel.Warning, Message = "Language model ({Provider}) gave no answer, next try in 15 minutes: {Problem}")]
|
||||
private static partial void LogFailed(ILogger logger, string provider, string problem);
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Error, Message = "Language model: the request failed in an unforeseen way")]
|
||||
private static partial void LogUnforeseen(ILogger logger, Exception exception);
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Warning, Message = "Language model ({Provider}) used more than the request allowed: {Cost} against an estimate of {Estimate}")]
|
||||
private static partial void LogAbove(ILogger logger, string provider, decimal cost, decimal estimate);
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Warning, Message = "Language model: {Rejected} of {Total} verdicts thrown away: {Problems}")]
|
||||
private static partial void LogRejected(ILogger logger, int rejected, int total, string problems);
|
||||
}
|
||||
@@ -5,7 +5,6 @@ using Anubis.Data;
|
||||
using Anubis.Db;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Microsoft.ML.OnnxRuntime;
|
||||
|
||||
namespace Anubis.News;
|
||||
|
||||
@@ -85,9 +84,9 @@ public sealed partial class NewsCollector(HttpClient http, Database db, IClock c
|
||||
catch (OperationCanceledException) when (stopping.IsCancellationRequested)
|
||||
{
|
||||
}
|
||||
catch (Exception e) when (e is HttpRequestException or IOException or InvalidDataException or OperationCanceledException or OnnxRuntimeException
|
||||
or UnauthorizedAccessException)
|
||||
catch (Exception e) when (!stopping.IsCancellationRequested)
|
||||
{
|
||||
// Of any kind, a native library that does not load included: without the model the keywords work alone.
|
||||
LogModelFailed(_logger, e.Message);
|
||||
}
|
||||
}, CancellationToken.None);
|
||||
@@ -121,7 +120,15 @@ public sealed partial class NewsCollector(HttpClient http, Database db, IClock c
|
||||
// The second judgement first (10.2 point 5), so the rules read it in the same round.
|
||||
if (Analyst is not null)
|
||||
{
|
||||
await Analyst.RunOnceAsync(cancellationToken).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
await Analyst.RunOnceAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
// The analyst is optional (10.3): whatever happens to it, the diary of the news is written.
|
||||
LogAnalystFailed(_logger, ex);
|
||||
}
|
||||
}
|
||||
|
||||
if (Watcher is not null)
|
||||
@@ -193,8 +200,9 @@ public sealed partial class NewsCollector(HttpClient http, Database db, IClock c
|
||||
|
||||
return result;
|
||||
}
|
||||
catch (Exception ex) when (ex is HttpRequestException or FormatException or IOException || (ex is OperationCanceledException && !cancellationToken.IsCancellationRequested))
|
||||
catch (Exception ex) when (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
// Of any kind: a source that cannot be read is tried again later and never stops the others.
|
||||
LogFailed(_logger, source.Name, ex.Message);
|
||||
await _store.RecordCheckAsync(source, ok: false, null, null, ex is OperationCanceledException ? "Nessuna risposta in 30 secondi." : ex.Message, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
@@ -238,6 +246,9 @@ public sealed partial class NewsCollector(HttpClient http, Database db, IClock c
|
||||
[LoggerMessage(Level = LogLevel.Information, Message = "News from {Source}: {Added} new articles in {Stories} stories")]
|
||||
private static partial void LogRead(ILogger logger, string source, int added, int stories);
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Error, Message = "The news analyst failed, the rules go on without it")]
|
||||
private static partial void LogAnalystFailed(ILogger logger, Exception exception);
|
||||
|
||||
[LoggerMessage(Level = LogLevel.Warning, Message = "News source {Source} failed: {Error}")]
|
||||
private static partial void LogFailed(ILogger logger, string source, string error);
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
using System.Globalization;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Anubis.News;
|
||||
|
||||
@@ -24,7 +26,7 @@ public sealed record VerdictOutcome(int Item, NewsVerdict? Verdict, string? Prob
|
||||
/// inside a tag, so it cannot close the tag or pass for instructions, and nothing in the answer can act except the
|
||||
/// fields of the schema, each checked here. Whatever does not fit is thrown away.
|
||||
/// </summary>
|
||||
public static class NewsVerdicts
|
||||
public static partial class NewsVerdicts
|
||||
{
|
||||
/// <summary>Changes with the instructions or the schema: answers cached under an older version are asked again.</summary>
|
||||
public const int Version = 1;
|
||||
@@ -142,13 +144,26 @@ public static class NewsVerdicts
|
||||
return All("risposta non in JSON");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return ReadAll(document, items, All);
|
||||
}
|
||||
catch (InvalidOperationException)
|
||||
{
|
||||
// Valid JSON, but a name that is not valid Unicode: reading it throws.
|
||||
return All("testo non valido");
|
||||
}
|
||||
}
|
||||
|
||||
private static List<VerdictOutcome> ReadAll(JsonDocument document, IReadOnlyList<AnalystItem> items, Func<string, List<VerdictOutcome>> all)
|
||||
{
|
||||
using (document)
|
||||
{
|
||||
var root = document.RootElement;
|
||||
if (root.ValueKind != JsonValueKind.Object || root.EnumerateObject().Count() != 1 || !root.TryGetProperty("verdicts", out var verdicts) ||
|
||||
verdicts.ValueKind != JsonValueKind.Array)
|
||||
{
|
||||
return All("risposta fuori dallo schema");
|
||||
return all("risposta fuori dallo schema");
|
||||
}
|
||||
|
||||
var byItem = items.ToDictionary(i => i.Item);
|
||||
@@ -158,16 +173,23 @@ public static class NewsVerdicts
|
||||
if (element.ValueKind != JsonValueKind.Object || !element.TryGetProperty("item", out var number) || number.ValueKind != JsonValueKind.Number ||
|
||||
!number.TryGetInt32(out var item) || !byItem.TryGetValue(item, out var source))
|
||||
{
|
||||
return All("giudizio senza un numero valido");
|
||||
return all("giudizio senza un numero valido");
|
||||
}
|
||||
|
||||
if (found.ContainsKey(item))
|
||||
{
|
||||
return All("due giudizi per la stessa notizia");
|
||||
return all("due giudizi per la stessa notizia");
|
||||
}
|
||||
|
||||
var (verdict, problem) = Read(element, source);
|
||||
found[item] = new VerdictOutcome(item, verdict, problem);
|
||||
try
|
||||
{
|
||||
var (verdict, problem) = Read(element, source);
|
||||
found[item] = new VerdictOutcome(item, verdict, problem);
|
||||
}
|
||||
catch (InvalidOperationException)
|
||||
{
|
||||
found[item] = new VerdictOutcome(item, null, "testo non valido");
|
||||
}
|
||||
}
|
||||
|
||||
return [.. items.Select(i => found.TryGetValue(i.Item, out var outcome) ? outcome : new VerdictOutcome(i.Item, null, "nessun giudizio"))];
|
||||
@@ -236,11 +258,17 @@ public static class NewsVerdicts
|
||||
{
|
||||
var text = value?.Trim();
|
||||
if (string.IsNullOrEmpty(text) || text.Length > MaxSummary || text.Any(c => char.IsControl(c) || c is '<' or '>' or '[' or ']' or '{' or '}' or '*' or '`' or '#' or '|' or
|
||||
'\\' or '_' or '~' or '@') || text.Contains("://", StringComparison.Ordinal) || text.Contains("www.", StringComparison.OrdinalIgnoreCase))
|
||||
'\\' or '_' or '~' or '@') || text.Contains("://", StringComparison.Ordinal) || text.Contains("www.", StringComparison.OrdinalIgnoreCase) ||
|
||||
Address().IsMatch(text) || text.Any(c => char.GetUnicodeCategory(c) is UnicodeCategory.Format or UnicodeCategory.LineSeparator or UnicodeCategory.ParagraphSeparator or
|
||||
UnicodeCategory.PrivateUse))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return text;
|
||||
}
|
||||
|
||||
// "coinbase-support.com", "t.me/x"; not "3.5%", not "milioni.La" (a missing space after a full stop).
|
||||
[GeneratedRegex(@"[\p{L}\p{N}-]{2,}\.(?:[a-z]{2,}|[A-Z]{3,})(?!\p{L})|\.[A-Za-z]{2,}/")]
|
||||
private static partial Regex Address();
|
||||
}
|
||||
Reference in new issue
Block a user