kolibri icon indicating copy to clipboard operation
kolibri copied to clipboard

AI-assisted search and discovery in Learn

Open akolson opened this issue 1 month ago • 1 comments

❌ This issue is not open for contribution. Visit Contributing guidelines to learn about the contributing process and how to find suitable issues.

Overview

A learner enters a question or a few keywords in the Library search bar. Learn prioritizes the best-matching resources available on the device. When the device can run a small language model, Learn also provides a short summary explaining how the resources address the learner’s question, along with additional ways to explore the content. The summary draws only on resources available on the device. It helps learners find relevant content without replacing the resources themselves.

The UI gets all results, AI sections and suggestions from the Kolibri search API. Behind the API, all channel resources, including ZIM content, are embedded in advance (kolibri-ecosystem#51). django-vectors searches these embeddings (#15268). Both models run offline behind OpenAI-compatible APIs. The small embedding model is a lightweight encoder that embeds only the learner’s query, and it does not generate text.

The feature works in two states:

  • With a language model: the device has a language model and a small embedding model. A language model without an embedding model is not supported.
  • Without a language model: search uses vector search when the device has a small embedding model, and keyword search otherwise, as it currently works. The UI shows the same sections for both.

In this phase, an admin sets up the models through the CLI or the Kolibri configuration. The state follows what is set up, and the UI has no setting for it. If a model that is set up does not work, search degrades gracefully, and the learner sees no error.

Long-term direction

Kolibri detects acceptable hardware, and whether the device supports a language model or embeddings. It asks the user to opt in before it downloads or imports the models. Model management, including turning AI search on or off, moves to the UI. Until then, model management by non-technical users is deferred.

This table shows which source feeds each part of the Learn UI in each state:

UI area With a language model Without a language model
Results list Vector matches, selected and ordered by the language model Vector matches, or keyword matches when vector search is not available
AI summary Language model Hidden
Suggested filters Uncertain filter matches from the learner's text, then the language model's suggestions Uncertain filter matches from the learner's text, then the most frequent labels among the first page of results
“More to explore” Queries that the language model used, each with up to 3 results Hidden
Related questions and similar topics Language model Hidden
Autocomplete resources Vector matches Vector matches, or keyword matches when vector search is not available

The learner’s language preference (#15042) filters every search request.

This issue covers the Learn plugin and everything it needs to work.

Description and outcomes

The Figma page "V2 - Learn" is the visual guide. The design is a work in progress. Where this issue and the design differ, this issue applies.

Library page Results page Search inside a channel
Library page with the Learn something new box Results page at level lm with the AI sections Search results inside a channel

Library page

  • [ ] Only with a language model, a “Powered by AI · Learn more” label appears in the row above the search bar, opposite the language chip from #15045. The page gets the state from the search status request, before any search runs.
  • [ ] “Learn something new” shows up to four searches that the language model suggested most often on this device. It is hidden when there are none.

Autocomplete

  • [x] When the learner focuses the empty search bar, the dropdown shows two groups: History (up to 5 resources the learner can resume) and Recent searches (up to 10, stored on the device for each user).
  • [x] As the learner types, the dropdown shows up to 3 matching filters, then up to 3 matching resources.
  • [x] Search inside a channel uses the same dropdown.

Results page

  • [ ] While the search runs, the results area shows a loading indicator.
  • [ ] The AI summary appears above the results. It is 2 to 4 sentences, names the resources it relates to, and can contain formatting and formulas.
  • [ ] The summary shows the disclaimer "This response is generated with AI. Verify any critical information for accuracy.", an "Elaborate" button and a regenerate button. "Elaborate" writes a longer summary, and regenerate writes the summary again. If the language model is busy or too slow, the current summary stays, with no error message.
  • [ ] Applied filters appear as chips. When a word in the query names a filter with certainty, for example “videos” and “Watch”, the filter is applied automatically, and the learner can remove it.
  • [ ] Suggested filters appear after "Add:", at most 3: first the uncertain matches from the query, then the suggestions from the table above. When the learner adds one, it moves to the applied chips, the results update, and the summary is written again for the new filters.
  • [ ] Similar topics appear as a card in the results grid, and related questions as a list below the results. Selecting one runs it as a search.
  • [ ] "More to explore" lists the queries that the pipeline used, each with its count and up to 3 result cards, for example "square root equations · 24 results ›". Selecting the count runs that query as a search.
  • [ ] When search uses vector search, ZIM pages appear in the results next to channel resources, ranked by relevance. Opening one goes to the page through its deep link.

Search inside a channel

  • [ ] Search within a channel uses the same results page, under the page title “Search results in ‘{channel or folder name}’”.
  • [ ] Opening a folder from the results preserves the current behavior: the learner navigates to that folder’s location within the channel.

Connected parts

The Learn UI uses these parts itself:

Part What it provides to the UI Boundary Issue
Kolibri search API Search results, AI sections, suggested searches, search_level, the search status, and the filter labels in the matching results The front-end contract in the next section This issue
Language preference The language for every request The language parameter in the route, initialized by the store #15042, #15044, #15045

The UI does not call these parts. They reach the UI only through the Kolibri search API:

  • Keyword search on channels matches by title and description, filtered by the base language (#15043).
  • The language model interprets the query, scores resources and writes the summary, through OpenAI-compatible chat completions. The pipeline receives the learner’s text as typed. It can run inside or outside Kolibri (kolibri-ecosystem#51).
  • The small embedding model embeds the learner’s query through the OpenAI-compatible embeddings API. It must be the same model and version that embedded the content (kolibri-ecosystem#51).
  • The vector store finds resources that match the query by meaning. The API returns them in the same result shape as keyword matches (#15268).
  • ZIM pages are the Wikipedia pages in ZIM files, stored as virtual content nodes (#14859). Vector search finds individual pages, and they link in the same way as content nodes. Each page gets its own thumbnail: an image from the page, or an image from a linked page if the page has none (images from linked pages can use more storage but provide thumbnails for pages without images).
  • Content embeddings for all channel resources, including ZIM content, are packaged with the content (kolibri-ecosystem#51).

The front-end contract

This section defines the API contract owned by this issue. The field names below are proposals for review.

Search request

This extends the existing content node search. It accepts the learner's search text, the current filters, and the language parameter introduced in #15044. The search text is passed through one of two parameters:

  • search always skips the language model and is used for autocomplete.
  • question uses the language model when one is set up and is used for full searches, triggered by pressing Enter or clicking the search button. develop already sends question for full searches.

In addition to the existing fields (results, more, and labels), the response includes search_level: "lm", "vector", or "keyword". "lm" means that a language model and an embedding model are set up on the device. In this phase, this is an on-device small language model, although a larger model could be used in some cases. The UI displays AI sections only when search_level is "lm".

The existing labels field already lists only the filter values in the matching results, so All filters and the suggested filters offer only values that would return results. Vector search and language model search return their matches as a ContentNode queryset, filtered by the matched IDs, so the existing labels code works without changes. This matters for vector search, because django-vectors keeps the vectors in a separate database with no join to ContentNode (#15268).

If vector search does not respond, the request falls back to keyword search for that request and still returns results.

Vector search and language model search return their results as one ranked page, in order of relevance, with up to max_results results and more empty. Keyword search keeps its current paging.

With a language model, the language model selects and ranks the results. The response to question also includes the AI fields below. All fields are optional, and the UI displays only the sections included in the response. The language model writes its text in the interface language when it is one of the request's languages, and otherwise in the first of the request's languages. With no languages in the request, it writes in the interface language.

  • summary: Summary text in Markdown, including LaTeX where needed.
    {"summary": "To solve $x^2 = 9$, take the square root of both sides, so $x = 3$ or $x = -3$. The video **Solving square root equations** shows this step by step."}
    
  • suggested_filters: A list of {key, value} pairs. The UI removes any that it already shows or that are applied.
    [
      {"key": "learning_activities", "value": "<WATCH id>"},
      {"key": "categories", "value": "<Algebra id>"}
    ]
    
  • explore_groups: A list of {query, count, results} objects, one for each query that the pipeline used. count is the number of keyword matches for that query, with the same filters. results holds up to 3 of those matches, in the same result shape as results.
    [
      {"query": "square root equations", "count": 24, "results": [{"id": "…", "title": "…"}]},
      {"query": "perfect squares", "count": 12, "results": [{"id": "…", "title": "…"}]}
    ]
    
    Only keyword search pages through every match. A new search with a language model or vector search returns one ranked page, so it can show fewer results than the count.
  • related_questions and similar_topics: Lists of strings. Each string runs as a search when the learner selects it.
    {
      "related_questions": ["How do you find the square root of a number?", "What is a perfect square?"],
      "similar_topics": ["Exponents", "Pythagorean theorem"]
    }
    

If the language model is busy, the question request returns an error immediately without waiting. If it doesn't respond within the time limit, the request also returns an error. In either case, the UI retries the search using search and displays the results without AI sections or an error message.

Only successful responses are cached, by query text, filters, language, and summary length. Repeating a search with the same inputs reuses the cached response without running the language model again.

The question request accepts two optional parameters for the summary buttons:

  • elaborate: when true, the language model writes a longer summary. The longer summary is cached on its own.
  • regenerate: when true, the request skips the cache, and the new response replaces the cached one.

When either request fails because the language model is busy or too slow, the UI keeps the current summary and does not retry with search.

Suggestions request

This request returns up to four suggested searches, for the “Learn something new” box:

{"searches": ["What is a perfect square?", "Exponents"]}

Each string runs as a search when the learner selects it. The searches are the related questions, similar topics and "More to explore" queries that the language model suggested most often on this device, in the request's languages. Only text that the language model wrote is shown, so no learner's own search reaches other learners. An empty list hides the box.

Search status request

This request returns the level that a full search would use right now, so a page can show the right sections before any search runs. The Library page uses it for the "Powered by AI" label.

{"search_level": "lm"}

search_level takes the same values as in the search response. The request does not call any model. Its answer comes from the models that are set up and from the result of the last model call. A busy language model still counts as "lm". Learners can make this request, and the response contains nothing about the models' addresses or settings.

Result shape

Vector matches and ZIM pages use the same result shape as the existing ContentNode results. ZIM page results link in the same way as content nodes.

Rendering the summary

The summary text is Markdown, and it can contain LaTeX formulas. The UI renders the formatting and the formulas safely:

  • HTML in the model's text never renders as HTML.
  • Formulas render on every supported browser, and screen readers can read them.
  • Broken Markdown or broken math never breaks the page.

The feature has no rendering code of its own. It uses the Markdown component from #15598, which renders through SafeHTML. Other parts of Kolibri can reuse the component.

Resources

Accessibility Requirements

  • The AI summary is exposed as a labelled region. When it becomes available, it is announced politely without moving focus.
  • While the search runs, the results area exposes its busy state to assistive technology.
  • Formulas include MathML, so screen readers can interpret them.
  • The autocomplete follows the combobox pattern. Each group ("History" and "Recent searches") has an accessible label. Arrow keys navigate the options, and Escape closes the dropdown.
  • Each suggested filter is a button with a descriptive accessible name, such as "Add filter: Algebra".
  • The "Elaborate" and regenerate buttons have accessible names.
  • The layout supports right-to-left (RTL) languages.
  • All new text is translatable.

Acceptance Criteria

  • [ ] The UI shows the sections for the state that search_level reports, and only those sections.
  • [x] Autocomplete sends search, never question.
  • [ ] A full search with text sends question.
  • [ ] The "Powered by AI" label follows the search status request.
  • [ ] Every request carries the global language parameter, when selected. All results, AI sections and suggested searches are limited to the preferred languages.
  • [ ] A search with no text, for example only categories, sends no question, so the language model does not run.
  • [ ] When the question request returns an error code or times out, the UI repeats the search with search, and it shows the results without AI sections and with no error message.
  • [x] Each autocomplete group shows no more than its limit.
  • [ ] Tests cover each value of search_level, the fallback to search when the question request fails, a filter change, and a search with no text.

Risks and open questions

  • Classroom load. The primary use case involves many learners sharing a device, but the language model runs slowly on small devices (about 6 tokens per second on a Raspberry Pi 5). With a language model, the results wait for it. When it is busy, the UI falls back to search, so learners still get results quickly. Test on real hardware.
  • Multilingual vector search. The vector store cannot filter by multiple languages in a single query (#15268). Preferences with multiple languages may slow searches, but results must still be restricted to the preferred languages.
  • Content vector table. Kolibri's content vector table, and loading the packaged embeddings into it, are not yet specced or scoped. Until they land, neither vector search nor the lm level can run on a real device.
  • ZIM pages in keyword search. In this phase, vector search finds individual ZIM pages, while keyword search finds only the ZIM resource as a whole. Testing is still needed to assess keyword search behavior for individual ZIM pages.
  • Search on another device. ❓ Open question: can a search through Explore Libraries use the other device's language model? A device on Kolibri 0.20 or later receives question unchanged, so it would run its own model. Until the team answers, the public endpoint keeps the keyword search, so a search on another device uses neither of that device's models.
  • Count wording. A "More to explore" count can be larger than the results that its search shows. UI string review settles the wording.

Out of scope for this issue

  • Search in Coach and in the admin and device pages.
  • The content embedding pipeline and the distribution of models and embeddings (kolibri-ecosystem#51).
  • Serving the models, and installers for them.
  • Setting up the model endpoints, including a warning when an endpoint is not on the device.
  • The django-vectors library (#15268).
  • Kolibri's content vector table and loading the packaged embeddings into it.
  • Importing ZIM files and their virtual content nodes (#14859).
  • Collecting search terms, and the thumbs feedback buttons (#13760).
  • Skeleton loaders for the results (#12873).
  • Detecting the language of the learner's text.

AI usage

akolson drafted this issue with Claude Code from #14023 and its linked issues, the Figma page "V2 - Learn", the concept note, the django-vectors spec and the prototype branch. akolson set the scope and the team's answers to the open questions decided the contract. rtibbles then used Claude Code to check this issue against its sub-issues and the design frames, and decided the revisions: an embedding model required alongside a language model, "Add:" built in Learn, result cards in "More to explore", the language rule for AI text, and suggested searches drawn only from the language model's own text. Both reviewed and edited each revision.

akolson avatar Oct 12 '26 11:10 akolson

I'm helping @jamalex prototype the ai_search plugin for an on-device test on Android (Pixel 9 Pro). It follows this breakdown: the ports, the stages, the AI_SEARCH_* options, and the decline/busy/failed behaviour. There is one place where we'd like to try something different: how the search request returns its results.

Even on a flagship phone, the full pipeline takes about 14 s. On low-end devices it could easily take over a minute: this issue estimates about 6 tokens/s on a Pi 5, which would hit the 60 s AI_SEARCH_QUESTION_TIMEOUT before the summary finishes. With several learners searching on one device, and AI_SEARCH_MAX_CONCURRENT at 1, later requests wait behind earlier ones or get turned away as busy.

A synchronous ?question= GET holds a server thread for the whole wait. The Android app runs CherryPy with only 2 threads, so a single search ties up half the pool. Raising the thread count costs memory, and it doesn't help with the timeout or the queueing.

So the prototype is going to try this instead:

  • ?question= starts the pipeline on a background thread and returns immediately. The response has keyword results, search_level: "pending" and a search id.
  • The frontend polls a result endpoint with that id. The endpoint reports progress (which stage is running, or the learner's place in the queue) and returns the summary as it is generated. When the pipeline finishes, it returns the final ranked page.
  • The learner can work with the keyword results the whole time, and a slow device just means a longer wait for the summary, not a failure.

We'll report back here with timings from the device. If we go this way, it changes the response contract in #15731 and #15740, so it would be good to discuss it here before those are implemented.

jamalexbot avatar Nov 10 '26 23:11 jamalexbot