EcoVal Changelog v0.9.1

How the calculations are built, part 7: the AI assistant

The assistant answers questions about EcoVal: what a number means, how it is worked out, where its data comes from. It computes nothing. Every figure in an answer comes from the documents in docs/assistant/ or from the visitor's own results sent with the question, and the code around the language model exists to keep it that way: a question the documents cannot answer costs nothing and gets a fixed reply, and an answer that cites something it was not given is never shown.

This part explains that code, from the documents to the streamed answer. The plan it was built from, with what was measured on the way, is next-steps-assistant.md. File paths are relative to backend/EcoVal.Api/Features/Assistant/ unless said otherwise. Code excerpts are copied from the source and shortened; // … marks what is left out.

Contents


1. Overview

A question goes through cheap checks first and the paid model call last. Everything before the model is deterministic and runs in the API; the only text the API sends for display that it did not choose itself is the model's answer, and that only after the check.

flowchart TD
    Q["Question, page language,<br/>section and its figures"] --> C1{"Empty, too long,<br/>budget spent?"}
    C1 -- yes --> F1["Fixed reply (code)"]
    C1 -- no --> E["Embed the question<br/>(e5, local)"]
    E --> S["Nearest 6 chunks,<br/>both languages"]
    S --> L["The question's language:<br/>most hits"]
    L --> G{"Gate: nearest<br/>within 0.17?"}
    G -- no --> F2["off_topic, no model call"]
    G -- yes --> P["Section's documents,<br/>second search with its title"]
    P --> X["Context: whole documents<br/>within 8,000 tokens"]
    X --> M["Claude Haiku 5.5,<br/>forced answer tool, streamed"]
    M --> V{"Answerable, cites only<br/>chunks it was sent?"}
    V -- yes --> D["done: sources"]
    V -- no --> F3["code: off_topic<br/>(takes the text back)"]

Two endpoints share these steps (AssistantPipeline): POST /api/assistant/ask returns the whole answer, and POST /api/assistant/ask/stream, which the site uses, sends it as server-sent events while it is written.


2. The documents and their chunks

Files: backend/EcoVal.Ingest/Assistant/AssistantDocParser.cs, AssistantRows.cs, AssistantDocsImporter.cs.

The assistant knows only docs/assistant/: one short document per topic, each in English and Swedish, with a front matter naming its page, the services it is about and its type (method, concept, reference). The ingest reads them into two tables:

  • assistant_docs: one row per document and language, with the whole Markdown;
  • assistant_chunks: one row per ## heading, with its text and its embedding.

A chunk is the unit the search finds and the model cites. Its id is the document's key and the slug of the English heading at the same place, so a Swedish chunk shares its English twin's id (forest/carbon-value.method#why-the-climate-cost-is-often-large in both). The checker in npm test makes sure the twins have the same headings in the same order, and the ingest refuses a pair that does not.

var id = $"{doc.Key}#{AssistantDocParser.Slug(english.Chunks[position].Heading)}";
var headingPath = $"{doc.Title} – {chunk.Heading}";
var embeddingText = $"{headingPath}\n\n{chunk.Text}";
return new ChunkRow(
    id,
    position,
    chunk.Heading,
    headingPath,
    chunk.Text,
    (int)Math.Ceiling(embeddingText.Length / perToken),
    embeddingText,
    AssistantDocParser.Sha256($"{modelName}\n{embeddingText}"));

What is embedded is the chunk with its document's title and heading in front, so that a short paragraph still says what it is about. The content hash covers that text and the model's name, and the importer embeds a chunk again only when its hash changes: editing one paragraph re-embeds one chunk, and a run with nothing changed never loads the model.

Token counts are estimates, characters divided by a factor per language, since Swedish words split into more tokens:

tokens≈⌈charactersc⌉,c={4English3Swedish\text{tokens} \approx \left\lceil \frac{\text{characters}}{c} \right\rceil, \qquad c = \begin{cases} 4 & \text{English} \\ 3 & \text{Swedish} \end{cases}

3. Embeddings: text as 384 numbers

File: backend/EcoVal.Embeddings/E5Embedder.cs.

An embedding turns a text into a vector, here 384 numbers, such that texts of like meaning get vectors pointing the same way. EcoVal uses intfloat's multilingual-e5-small, run locally with ONNX Runtime on the CPU: nothing is sent anywhere to embed a question, and it takes tens of milliseconds. The model is multilingual, so "Hur räknas kolvärdet?" lands near "How is the carbon value calculated?".

The model was trained with two prefixes, and searches badly without them: stored texts are embedded as passage: … and questions as query: ….

public float[] EmbedQuery(string question) => Embed("query: " + question);

public float[] EmbedPassage(string passage) => Embed("passage: " + passage);

The model gives one vector per token; the embedding is their mean (mean pooling), scaled to length 1. With hth_{t} the model's output for token tt of nn:

hˉ=1n∑t=1nht,e=hˉ∥hˉ∥\bar{h} = \frac{1}{n} \sum_{t=1}^{n} h_t, \qquad e = \frac{\bar{h}}{\lVert \bar{h} \rVert}
for (var token = 0; token < ids.Length; token++)
{
    for (var d = 0; d < Dimensions; d++)
    {
        embedding[d] += hidden[0, token, d];
    }
}
var length = 0.0;
for (var d = 0; d < Dimensions; d++)
{
    embedding[d] /= ids.Length;
    length += embedding[d] * (double)embedding[d];
}
var scale = (float)(1 / Math.Sqrt(length));
// … every number multiplied by scale

Because every embedding has length 1, how alike two texts are is the cosine of the angle between their vectors, which is their dot product. The search uses the cosine distance, 0 for the same direction:

d(q,c)=1−cos⁡θ=1−∑k=1384qk ckd(q, c) = 1 - \cos\theta = 1 - \sum_{k=1}^{384} q_k \, c_k

In practice e5's distances sit close together: on the test questions an answerable question's nearest chunk is 0.075–0.161 away, and an off-topic one's 0.146–0.223. That is why the threshold in section 5 is set from measured questions, not guessed.


4. The search and the question's language

Files: AssistantFeature.cs (AssistantLookups), QuestionLanguage.cs.

The chunks' embeddings are stored in PostgreSQL with the pgvector extension, which compares vectors with <=> (the cosine distance) and keeps an HNSW index on them, so the nearest chunks are found without comparing the question with all 1,232. EF Core writes the query:

public async Task<IReadOnlyList<ChunkHit>> NearestChunksAsync(float[] question, int take, string? language, CancellationToken cancellationToken)
{
    var vector = new Vector(question);
    return await db.AssistantChunks
        .Where(chunk => language == null || chunk.Language == language)
        .OrderBy(chunk => chunk.Embedding.CosineDistance(vector))
        .Take(take)
        .Select(chunk => new ChunkHit(chunk.Id, chunk.DocKey, chunk.HeadingPath, chunk.Text, chunk.Embedding.CosineDistance(vector), chunk.Language))
        .AsNoTracking()
        .ToListAsync(cancellationToken);
}

The first search covers both languages. The browser sends the page's language, but a visitor may ask in Swedish on the English page; searched in English only, such a question sat about 0.06 further from every chunk and mostly failed the gate. Searched in both, a question lands nearest the chunks in its own language: on the test set, the nearest chunk shared the question's language for all 57 questions the documents answer or should decline, ahead of its twin in the other language by 0.02–0.10. So the question's language is read from the hits, the page's language deciding only a tie:

language={ennen>nsvsvnsv>nenthe page’sotherwise\text{language} = \begin{cases} \text{en} & n_{\text{en}} > n_{\text{sv}} \\ \text{sv} & n_{\text{sv}} > n_{\text{en}} \\ \text{the page's} & \text{otherwise} \end{cases}

where nenn_{\text{en}} and nsvn_{\text{sv}} count the six nearest hits in each language.

public static string Of(IReadOnlyList<ChunkHit> hits, string siteLanguage)
{
    var english = hits.Count(hit => hit.Language == "en");
    var swedish = hits.Count(hit => hit.Language == "sv");
    return english > swedish ? "en" : swedish > english ? "sv" : siteLanguage;
}

From here on everything is in that language: the hits kept, the documents sent and the language the model is told to answer in. The done event carries it, and the browser marks the answer's text with lang, so a screen reader reads a Swedish answer on the English page as Swedish.


5. The gate

Files: AssistantGate.cs, AssistantOptions.cs (GateMaxDistance, GateHits).

The gate stops a question the documents cannot answer before any paid call. It passes when the nearest hit in the question's language is at most dmax⁡d_{\max} away, and keeps only the hits within it:

pass  ⟺  min⁡id(q,ci)≤dmax⁡=0.17\text{pass} \iff \min_i d(q, c_i) \le d_{\max} = 0.17
public static GateResult Check(IReadOnlyList<ChunkHit> hits, AssistantOptions options)
{
    if (hits.Count == 0) return GateResult.FailedResult;
    var sorted = hits.OrderBy(h => h.Distance).ToList();
    var best = sorted[0].Distance;
    return best <= options.GateMaxDistance
        ? new GateResult(true, best, sorted.Where(h => h.Distance <= options.GateMaxDistance).ToList())
        : new GateResult(false, best, []);
}

The chart shows the nearest distance for each of the 63 questions in docs/assistant/questions.json, by what the question should get. Every answerable question and every one the assistant should decline passes; five of the six off-topic ones are stopped. The grey row is the same answerable questions searched in the other language only, as the search was before it covered both: eleven of fifty would have passed.

The gate's distances for the 63 test questions

The gate is not the last line. An off-topic question that slips through ("Vad blir det för väder i Stockholm i morgon?" sat at 0.146) reaches the model, which is told to answer only from the documents; it replies that it cannot, and the visitor gets the same off_topic code. The gate only saves the call. Each decision is recorded in a histogram (ecoval.assistant.gate.distance, tagged passed or not), so the threshold can be checked against real questions.


6. A question asked from a section

Files: AssistantPipeline.cs (PrepareAsync, SectionHitsAsync), AssistantFeature.cs (DocKeysForServiceAsync).

"Ask" on a section of the results sends the section's key (page and service, such as forest and stand) and its figures. Questions asked that way are often vague: "where does this data come from?", "why is this so high?". Three things make them answerable.

The section's own documents, first. Every document listing the service is sent. A document's front matter lists its own service first, and others after (growth.method is about [climate, stand], so it is climate's), so the section's documents are ordered with its own first, methods before concepts, the narrowest first:

.Where(doc => doc.Language == language && doc.Page == page && doc.Services.Contains(service))
.OrderBy(doc => doc.Services[0] == service ? 0 : 1)
.ThenBy(doc => doc.Type == "method" ? 0 : 1)
.ThenBy(doc => doc.Services.Length)
.ThenBy(doc => doc.Key)

The section named. The first document's title, from the database, names the section in the prompt (see section 8), and the instructions say that "this", "here" and "these figures" mean it. Without it the model refused "where does this data come from?" from the stand three times in four.

A second search, for the context only. Searched alone, a vague question lands near any document about data. So the question is searched again with the section's title in front, in the question's language, and the context is chosen from those hits:

private async Task<IReadOnlyList<ChunkHit>> SectionHitsAsync(
    string question, string section, string language, IReadOnlyList<ChunkHit> questionHits, CancellationToken cancellationToken)
{
    var vector = embedder.EmbedQuery($"{section}: {question}");
    var hits = await lookups.NearestChunksAsync(vector, options.Value.GateHits, language, cancellationToken);
    var near = hits.Where(hit => hit.Distance <= options.Value.GateMaxDistance).OrderBy(hit => hit.Distance).ToList();
    return near.Count > 0 ? near : questionHits;
}

For "where does this data come from?" from the stand, the nearest chunks alone were the stand's (0.134), then a dam's data (0.159) and the salmon figures' sources (0.160); with the title the three nearest were all the stand's own, from 0.070. The gate has already judged the question alone, so a section's title never helps an off-topic question through: "what is a good pizza recipe?" asked from the climate section still gets off_topic.

The figures. The section's figures on screen go with the question as result: names, numbers and units, never the outline or where it is. The frontend reads them when the question is sent (features/forest/assistant-values.ts for the stand and the climate section so far), named the way the documents name them so the model can match each to its method, with every range as low, central and high:

case 'climate':
  return climateValues(result);
// …
...range('climate cost of felling, forestry path', cost.forestrySek, 'kr'),
...cost.forestryParts.map((part) =>
  value(`climate cost of felling, forestry path, central, model years ${part.fromYear}–${part.toYear}`, part.sek, 'kr'),
),

With them, "why is this so high?" from the climate section is answered with the area's own climate cost by period. Without them it was refused every time, since the section shows several figures and "this" could be any.

Suggested questions. A section can offer two or three questions as buttons above the box, written in docs/assistant/suggestions.json with the English and Swedish side by side. Their answers are not written by hand: the ingest's AssistantSuggestionsImporter asks each one through this same pipeline, with the section attached and the same check (AssistantAnswerer, which the ingest gets from the API with AddAssistantAnswering), and stores the answer with the keys of the documents that were sent. A press shows that answer at once, with no model call. Since a stored answer is the same for every area, the questions are ones the documents answer without the visitor's figures. The answer is made again only when something it depends on changes:

h=SHA-256⁡(question, model, (k1: c1),…,(kn: cn))h = \operatorname{SHA\text{-}256}\bigl(\text{question},\ \text{model},\ (k_1{:}\,c_1), \dots, (k_n{:}\,c_n)\bigr)

where kik_i are the sent documents' keys, sorted, and cic_i their content hashes; a document that is gone counts as changed. A run with nothing changed costs nothing.


7. The context: which documents are sent

File: ContextBuilders.cs.

The model is given whole documents, not loose chunks (the spec's "Path C"): a method document is a few hundred words, and an answer about one part of it often needs another part. Which documents:

  1. the section's documents, when one is attached, in the order of section 6;
  2. the document of the nearest hit;
  3. the document of the next hit, if its best chunk is within a margin mm of the first document's best.
second document sent  ⟺  d2−d1≤m=0.05\text{second document sent} \iff d_2 - d_1 \le m = 0.05
var rankedHits = hits
    .GroupBy(hit => hit.DocKey)
    .Select(group => (Key: group.Key, Best: group.Min(hit => hit.Distance)))
    .OrderBy(doc => doc.Best)
    .ToList();

var fromHits = rankedHits
    .Take(1)
    .Concat(rankedHits.Skip(1).Take(1).Where(doc => doc.Best - rankedHits[0].Best <= options.SecondDocMargin))
    .Select(doc => doc.Key);

return pinned.Concat(fromHits).Distinct(StringComparer.Ordinal).ToList();

They are added in that order until the next would pass MaxContextTokens (8,000), so the cap drops documents from the end. The ones kept are then sorted by key, so the same documents always give the same text, byte for byte: the provider's prompt cache (section 8) needs an identical prefix.

A document over the cap on its own is sent as its matching chunks only, nearest first ("Path A"); the nearest is always sent. The chunk ids that went out are kept in the context, for the check in section 9.


8. The prompt and the cache

File: AssistantPrompt.cs.

The messages are laid out so that what is the same from question to question comes first, and nothing the visitor wrote ever reaches a system message:

Message Role Holds
1 system the instructions: answer only from <docs>, the answer's language, what <section> and <result> mean
2 system the documents, <docs><doc key="…" title="…">…</doc></docs>, with the cache breakpoint after them
3 … user, assistant the last three questions and answers of the conversation
last user <section> with the section's title, <result> with its figures, <question>
new(ChatRole.System, $"You are EcoVal's assistant. Answer only from <docs>. Reply in {languageName}. {SectionRule}"),
// The prompt cache's breakpoint, at the end of the documents: the tool, the instructions and the documents
// are read from cache when the next question gets the same documents (5 minutes; from 512 tokens on Haiku 5.5).
new(ChatRole.System, [new TextContent(context.DocsBlock).WithCacheControl(Ttl.Ttl5m)])

Everything up to the breakpoint (the tool's definition, the instructions, the documents) is cached by the provider for five minutes. A second question that gets the same documents reads them from cache at a tenth of the price: a first question with two documents cost about 6,700 input tokens, a follow-up read 7,016 of its 7,254 from cache.


9. The forced tool and the check

Files: AssistantPrompt.cs, ModelAnswer.cs.

The model does not answer in free text. It must call one tool, answer, whose input has three fields:

{
  "type": "object",
  "properties": {
    "answerable": { "type": "boolean" },
    "sourceChunkIds": { "type": "array", "items": { "type": "string" } },
    "answer": { "type": "string" }
  },
  "required": ["answerable", "sourceChunkIds", "answer"]
}

The call is made with ChatToolMode.RequireSpecific("answer"), so the reply is always that structure, never a paragraph to parse. Then the backend checks it, and shows the answer only if all three rules hold:

shown  ⟺  answerable  ∧  ∣S∣≥1  ∧  S⊆C\text{shown} \iff \text{answerable} \;\land\; |S| \ge 1 \;\land\; S \subseteq C

where SS is the set of cited chunk ids and CC the ids of the chunks that were sent.

public static bool IsValid(ModelAnswer? answer, AssistantContext context) =>
    answer is { Answerable: true, SourceChunkIds.Count: > 0 } &&
    answer.SourceChunkIds.All(context.ChunkIds.Contains);

A reply that fails any rule, or is not the tool call with the right types, becomes off_topic. Since the chunk ids are the same in both languages, a citation reads the same whichever language was asked, and the sources under the answer are the cited chunks grouped by document, in the order first cited.


10. Streaming the answer

Files: AssistantFeature.cs (StreamAnswer), AnswerStream.cs, AssistantStreaming.cs, EagerToolStreaming.cs, AssistantStreamResult.cs; in the frontend shared/assistant/stream-events.ts and assistant.ts.

An answer takes a few seconds to write; streamed, its first words appear after about 1.5 s. The stream is server-sent events with three types:

Event Data Meaning
delta text the answer's next text, to add to what came
done sources, language the whole reply passed the check; the last event
code code a fixed reply instead; after deltas it takes them back; the last event

A stream that ends with neither done nor code was cut off: the browser keeps what arrived, marked as such.

Reading JSON as it grows. The model writes the tool's input a few characters at a time, as JSON. AnswerStream takes each fragment and returns the answer's newly readable text, decoded; it rescans the whole object each time (answers are a few kilobytes) and leaves anything cut off at the end, half an escape or half a key, for the next fragment:

public string Feed(string fragment)
{
    if (fragment.Length == 0) return "";
    json.Append(fragment);
    Scan(json.ToString());
    var delta = Answer[sent..];
    sent = Answer.Length;
    return delta;
}

The field order the model chooses. The plan was to have answerable and sourceChunkIds first, check them, and only then pass the text on. Claude Haiku 5.5 often writes answer first whatever the schema's order. So the text is streamed at once and the whole reply is checked at the end; a code after deltas takes the text back. That is rare in practice: when the model cannot answer, its answer is empty. When the citations do come first and already fail, the stream stops showing anything at once, but reads the model's stream to its end, since the usage (and so the cost) comes last.

Two buffers in the way. Both held the whole answer back until it was complete, so neither streaming nor the caret showed anything until the end:

  • Anthropic's API buffers a tool's input unless the tool has eager_input_streaming. Microsoft.Extensions.AI's tool declarations cannot carry that flag, so EagerToolStreaming, a DelegatingChatClient, moves them into the request the Anthropic adapter builds, as the SDK's own tools with the flag set, for streamed calls only.
  • ASP.NET Core's TypedResults.ServerSentEvents held the stream back until it ended. AssistantStreamResult writes each event by hand and flushes it, and sets X-Accel-Buffering: no so a proxy such as Caddy does not buffer either.
await foreach (var item in events.WithCancellation(httpContext.RequestAborted))
{
    var data = JsonSerializer.Serialize(item.Data, JsonSerializerOptions.Web);
    await response.WriteAsync($"event: {item.EventType}\ndata: {data}\n\n", httpContext.RequestAborted);
    await response.Body.FlushAsync(httpContext.RequestAborted);
}

The browser reads the response text as it grows (HttpClient's progress events with partialText), and StreamEvents returns the events completed since the last read.


11. Cost, budget and limits

Files: ModelAnswer.cs (UsageCost), AssistantFeature.cs (AssistantBudget), AssistantMetrics.cs, backend/EcoVal.Api/RateLimiting/AssistantRateLimit.cs.

Cost of a call. From the tokens the provider reports. The adapter's input count holds every input token, of three kinds: read from the cache (TreadT_{\text{read}}, CachedInputTokenCount), written to it (TwriteT_{\text{write}}, reported in AdditionalCounts as CacheCreationInputTokens), and the rest, read fresh. Each kind, and the output, has its price per million: pinp_{\text{in}} 0.10, pwritep_{\text{write}} 0.125, preadp_{\text{read}} 0.01 and poutp_{\text{out}} 0.50 US dollars for Claude Haiku 5.5 with prompts up to 100,000 tokens (in AssistantOptions):

cost=(Tin−Tread−Twrite) pin+Twrite pwrite+Tread pread+Tout pout106\text{cost} = \frac{(T_{\text{in}} - T_{\text{read}} - T_{\text{write}})\,p_{\text{in}} + T_{\text{write}}\,p_{\text{write}} + T_{\text{read}}\,p_{\text{read}} + T_{\text{out}}\,p_{\text{out}}}{10^6}
var (fresh, written, cached) = InputTokens(usage);
var output = usage.OutputTokenCount ?? 0;
return (fresh * prices.InputPerMillion + written * prices.CacheWritePerMillion + cached * prices.CachedInputPerMillion
    + output * prices.OutputPerMillion) / 1_000_000m;

A first question with about 6,700 input tokens, nearly all of them written to the cache, and 425 output tokens costs about 0.001 US dollars; a follow-up that reads them from the cache, about 0.00046. (Until 23 Nov 2026 cache writes were counted at the plain input price, which made a first question about a sixth too cheap.)

The daily budget. Every call's cost is added to the day's total, in Swedish time, and when the total reaches DailyBudgetUsd (3.30 US dollars, a month's 100 over 30 days) every question gets budget_exhausted until midnight. The cost is added even when the visitor leaves mid-answer, since what the model wrote is paid for. The budget is kept in memory, so a restart of the API starts the day again; the provider's own spend limit, set on the account, is the hard stop.

Per visitor. Two fixed windows chained per client address, six questions a minute and sixty a day, with the valuations' 429 and rate_limited code:

return RateLimitPartition.Get(client, _ => RateLimiter.CreateChained(
    new FixedWindowRateLimiter(new FixedWindowRateLimiterOptions
    {
        PermitLimit = options.PerMinute,
        Window = TimeSpan.FromMinutes(1),
        QueueLimit = 0,
    }),
    new FixedWindowRateLimiter(new FixedWindowRateLimiterOptions
    {
        PermitLimit = options.PerDay,
        Window = TimeSpan.FromDays(1),
        QueueLimit = 0,
    })));

What is recorded. The meter EcoVal.Api.Assistant counts questions by outcome (too long, budget spent, stopped by the gate, refused, answered, failed), tokens by kind and the cost, and keeps the gate's distances as a histogram. Each call also writes one log line with the best distance, the number of documents, the tokens and the cost. Neither holds the question or the answer.


12. Summary of this part

Step Kind of calculation Fitted or learned?
Chunking and ids Splitting at headings; slugs of the English heading No
Embeddings A pretrained multilingual model (e5-small), run locally; mean pooling, unit length Pretrained by its authors; nothing trained by EcoVal
Search Cosine distance with pgvector's HNSW index No
The question's language Majority of the six nearest hits No; checked on the test set
Gate A threshold on the nearest distance Threshold chosen from the test set's distances
Context Pinned documents, nearest documents within a margin, a token cap, sorted by key No
Answer A language model (Claude Haiku 5.5) through a forced tool The provider's model
Check Three rules on the reply's structure and citations No
Cost Tokens times prices No

This is the one part of EcoVal that runs models trained by others on text. Two kinds of care follow from it. The model never computes a figure: it explains the documents' and the visitor's own. And nothing it writes is shown unless it says it can answer and cites only what it was given.