Channel knowledge (Ask)¶
Status: Built (ADR 0022). User guide: Ask.
Ask indexes what YouTube channels say in their videos (captions only), lets anyone search it, and answers questions about it in the chat panel with a numbered reference to the moment for every point. Code: backend/app/services/knowledge/, backend/app/api/ask.py, the Channels Ask can answer from section of Settings → Library (frontend/src/pages/settings/AskChannelsSection.tsx, frontend/src/pages/ask/), the Said in videos section of home search results (frontend/src/pages/library/SaidInVideos.tsx), the Ask panel (components/HelpChatPanel.tsx).
Data (revision 0022_ask_knowledge)¶
| Table | What it holds |
|---|---|
kb_channels |
One per Ask channel: canonical URL (unique), name, include_streams (default off), max_videos (null = all), status (queued / listing / indexing / ready / paused / error), the embedding model and dimension of its vectors, added_by (SET NULL) |
kb_videos |
One per upload: YouTube id, title, description, date, is_stream, position (0 = newest), fetch_status (pending / fetched / no_captions / members_only / failed), attempts and next attempt, caption_auto, cues (zlib JSON of [start_sec, text] lines of about 5 seconds), embedded_model, sponsor_segments (JSON [start, end, category] from SponsorBlock, null = none) and sponsor_checked_at (null = not asked yet; revision 0034_kb_sponsor_segments) |
kb_chunks |
Passages: start_sec, end_sec, text; chunk_index -1 is the title and description. kb_channel_id is denormalised for filtering |
kb_chunks_fts |
FTS5, external content on kb_chunks.text; triggers trg_kb_chunks_fts_insert / _update (AFTER UPDATE OF text) / _delete use the external-content 'delete' form |
kb_chunk_vectors |
chunk_id → float16 vector |
ask_threads, ask_messages |
Each user's saved Ask conversations (answers from channels, a video and Horde), with each answer's references, video or doc sources as JSON; scope keeps the last source (channels, video or help) |
ai_jobs.kb_channel_id serves the embed_kb_channel job. Nothing references the channel catalog: it trims beyond its cap, merges duplicates by deleting rows, and can be switched off. Progress counts are COUNT queries, never stored. Factory reset (erase media) deletes these tables.
Indexing¶
The ask worker (knowledge/worker.py, in the WorkerRegistry, off under HORDE_E2E) does one unit of work per pass:
- List a channel that is new, failed listing an hour ago, or was listed a day ago:
fetch_channel_feedfor the Videos tab (and Live wheninclude_streams), 100 per page, insidecall_gatedat background priority (knowledge/listing.py). Shorts are never listed; upcoming and live broadcasts are skipped. At most the channel's limit per tab (channels.effective_limit:kb_channels.max_videos, or the app settingask_max_videos, default 500). Rows that disappear from a listing are kept, unless they sit beyond the limit: those are deleted with their passages (indexing.apply_listing), which is how a lowered limit takes effect. Changing a channel's limit (PATCH /api/ask/channels/{id}max_videos, null = the app-wide one) or the app-wide limit queues a new listing. A channel added from a subscription's address that YouTube knows under the address of a channel already in Ask is dropped at its first listing (worker._is_duplicate). - Fetch one video's captions, newest upload first with channels taking turns (every channel's newest, then every channel's next, so each channel answers within minutes of being added) (
knowledge/captions.py): from the library copy's caption file when there is one, otherwise a subtitle-only yt-dlp call in the extract gate (downloads/subtitles.download_with_subtitles, which keeps a video's own captions over a dubbed audio track's captions translated back, see below). The call also returns the description and the upload date; the listing gives no exact date, sokb_videos.published_atis set here. A YouTube fetch runs only when no library caption retry is due andTimedtextPacer.try_reserve_background(15)succeeds; a rate limit (RETRY) backs the video off and blocks every caption fetch (services/timedtext.py). Other failures retry three times, an hour apart and growing. - Chunk (
knowledge/chunking.py):chapters.caption_linesmerges YouTube's rolling captions into 5-second lines that hold each word once; passages gather lines up to 75 seconds or 1,400 characters and start the next 15 seconds before the end. -
Embed (
knowledge/embed.py): after fetches and on idle passes, anembed_kb_channeljob is queued for any channel with passages not embedded with the current model. A job embeds 25 videos (text prefixed with channel, title and year), commits before each provider call, and queues the next batch.ai/worker._next_jobpicks library jobs first. Only videos embedded with the channel's model are searched, so changing the model re-embeds without mixing vector spaces. -
Sponsor segments (
knowledge/sponsorblock.py, ADR 0034):GET https://sponsor.ajay.app/api/skipSegmentswith the video's YouTube id and the categoriessponsor,selfpromoandinteraction(skip and mute segments only; intros and outros are left in, a podcast's intro previews the episode). It runs right after a video's captions are committed whenSponsorPacer(onAppContext.knowledge, one request per 3 seconds) allows, so it hides inside the 15-second spacing of YouTube fetches and holds no database lock; otherwise, and for videos indexed before this existed, a backfill pass asks about the next unasked video with captions, newest first (paused channels wait). 404 and 400 mean no segments; a timeout, 429, 5xx or unreadable answer leaves the video due and pauses every request for 10 minutes (the backfill asks the other videos before it again:SponsorPacer.failed), and never fails indexing. Each listing of a channel makes its videos younger than 30 days due again (asked more than 20 hours ago), since segments are often submitted days after upload; their old segments stay in use until the new answer.HORDE_ASK_SPONSORBLOCK=0turns the requests off.
Subscribing turns Ask on (channels.index_on_subscribe, from POST /api/follows/ask-index and after a download subscribes someone), whatever the channel's size. Subscriptions older than that are queued once by the worker at its first start (knowledge/subscriptions.py, flag ask_subscriptions_indexed in the app settings), without asking YouTube; a channel turned off afterwards stays off. Revision 0035_kb_keep_indexed_videos gave channels that already held more than 500 uploads their count as their own limit. AskChannelRead.channel_total is the channel's uploads on YouTube: the channel catalog's channel_total when it has one, else the listed count when the listing ended before the limit (ADR 0035).
Removing a channel deletes its passages in batches of 500 (the FTS triggers fire per row) before the channel; turning streams off deletes stream videos 50 at a time. The worker re-reads rows after every network call, so a channel removed or paused meanwhile is skipped. A listing cut off by a restart starts over (worker.recover).
Search¶
knowledge/search.py builds every MATCH expression itself: each term is a quoted phrase whose last word is cut to its stem and prefixed when it has a common ending ("dopamine fasting" → "dopamine fast"*, "batteries" → "batter"*; the index has no stemmer), and a lone word of four letters or more also matches its endings, stop words are dropped, terms are ORed and ranked by bm25, always with a LIMIT. Hostile input never reaches FTS5 syntax. GET /api/ask/search serves the Said in videos section of the home page's search results (every Ask channel; shown once one has passages); it links each hit to the caption line within the passage that shares the most words with the query (knowledge/moments.py), two seconds early. A hit at least half inside a SponsorBlock segment, or whose words match only in lines inside one, is skipped, and its moment is never an ad line (a line counts as ad when at least half of it, up to the next line's start, is inside a segment).
Chat¶
POST /api/ask/chat (knowledge/ask_chat.py) streams one turn:
- Source (
knowledge/routing.py): a question about Ask's indexing (routing.about_ask_channels: "is X indexed?") → Horde, even when it names a channel; elseanswer_from("Ask Horde instead" or "Ask \<video> instead" under an answer) → that source for this turn, whatever the question names; else "all my channels" → every channel with passages; channels the question names (name or handle, with or without "the", spaces or an's; a handle without an ending such as "lab" or "tv"; for a two- or three-word name, its last word when that is not an ordinary word, so "Huberman" names "Andrew Huberman"; initials of three or more words only in a "what does X say" question,routing.asks_what_said) → those; else thechannel_idsthe client sends (opened with "Ask", or the previous answer's channels) → those; else, with a video ( video, picked, orpage_video, the watch page's;resolve_videodrops it when video chat is off, and a downloaded stream becomes its library copy): Horde whenrouting.names_hordematches orhelp_data.topicsdoes androuting.about_videodoes not; thepage_channel_idwhenrouting.about_channelmatches ("this channel", "his other videos") with the watched video's passages ranked first; Horde whenrouting.about_hordematches andabout_videodoes not (for a picked video, only withrouting.asks_how_to); else the video. A picked video stays in the thread'sscopewhatever answers, and a new thread about a video is titled with it; without one, thepage_channel_id(a channel page) unless the question is about Horde; with no page channel and a question about neither Horde nor the user's things, the channelsknowledge/channel_guess.pypicks (embeddings shortlist three, the chat model at temperature 0 with their matching and newest titles names those that would answer, or none; ADR 0033) (routing.about_horde, withrouting.asks_how_toor withoutrouting.about_video: "how do I download his latest video?" is Horde's) → that channel; else Horde. A question that names no channel and reaches Horde gets a note listing the indexed channels (help_note._topic_note), and with one or two indexed channels the panel offers Ask \<channel> instead under the answer. The route picks this before streaming (ask_chat.pick_route), and saves a stream's row first (api/stream_ai.prepared_state; if that fails for the page's video, the turn is routed again without it). Eventsthreadandscope(withchannelsandvideo) say which, and the source beside the panel's title followsscopeunless a video is picked. - A video runs
ai.chat.run_chat_turnwith the Assistant model and a target (_VideoChat) whose context is the per-video chat's (ai/embeddings.build_chat_contextfor a library video: details, matching caption passages, saved comments;stream_ai.chat_contextfor a stream) and which saves both turns in the thread, the answer withsources{"kind": "video", "video": …}. - Horde runs
help_chat.stream_help_eventswith the saved history and a store that writes both turns to the thread. A question about indexing (routing.about_ask_channels) or about what a channel says (routing.asks_what_said) getsknowledge/help_note.for_question: every Ask channel with its status and progress (anyone may list them), and for each library channel it names that is not indexed, a note saying so, with that channel's library videos when the user allows their data. - Channels: check the AI is allowed and the Assistant model present before any cost; keep the channels with the most matching passages when there are more than the model compares (two for small, four otherwise). Then (
knowledge/retrieval.py):- Expand the question with one JSON call (skipped for small models):
terms(spellings captions use, generations, part names),subjects(the products, people or works it is about, as a title spells them),search(the question as one sentence) andrecent(the answer depends on what is newest). The call sees the last four messages, so a follow-up ("what about its battery?") is expanded with what it refers to. Without an expansion, a short or back-pointing follow-up is searched together with the user's previous question (search_question). - Watching: asked from a watch page whose video the channel has, the expansion and the answer are told its title, so "this device" means what it is about (
retrieval.watched_title). - Subjects that name a channel being searched are dropped: its title matches would be the channel talking about itself (a Discord invite, a studio tour).
- Search each channel: keyword and vector rankings, plus, counted twice, a keyword ranking of only the videos whose title names a subject (the battery passage of the Odin 3 review need not say "Odin 3"), fused by reciprocal rank (k = 60). Only when the answer changes over time (
recent: products and prices, what to buy now, software versions, news; never advice that does not age, such as repairs, maintenance, cooking, setup or one specific older model; or words such as "right now", "latest"), each score is weighed by its video's age: 0.8 at a year, about 0.6 at three, never below 0.45 (_boost_recent; an undated video is placed by its rank among the uploads). A question about the earliest of something ("his first Anbernic review", "originally":asks_earliest) runs the other way, from the channel's first video, and searches a subject's oldest videos first. - Pick the best videos' best non-overlapping passages, skipping caption passages under 80 characters (a video's last line) and sponsor reads: a passage at least half inside the video's SponsorBlock segments is left out, and one partly inside is rebuilt from its caption lines outside them (a copy, with its start and end moved; the stored passage is unchanged). Resolving references uses each video's lines without the ad lines, so a reference never opens at or quotes a sponsor read inside a kept passage. This runs on the rows already loaded, so it adds nothing to an answer's time, and already-indexed videos benefit without re-chunking or re-embedding. (three per video; ten, ranked first, for a video whose whole title is in the question:
retrieval.named_videos) within a fair share of the budget: 6,000 / 12,000 / 20,000 characters by model tier for a model on this network, 12,000 / 36,000 / 60,000 for a hosted one (ask_chat._budget). A question about the channel's newest videos ("what are his latest videos about?") first takes the title and description of its ten newest. - Format the excerpts numbered in date order, without times, under one heading per video: channel, title, upload date and the first paragraph of the description, which spells the names captions garble. Nothing found → a fixed answer, no model call.
- Expand the question with one JSON call (skipped for small models):
- The model (
ask_chat.system_prompt) answers with thinking off (think=False, OpenRouter'sreasoning: {enabled: false}; the query expansion too): a reasoning model thinking first was three times slower, and its thinking used the whole token budget, so the expansion JSON came back cut off and some answers empty. It is told to skip sponsor reads (the fallback for videos SponsorBlock has no segments for), that captions do not say who speaks (in a podcast or interview, credit the host or a guest only when the passage makes it clear, else "in the episode with …"), to report what the channel recommends rather than its own yes or no, and to mark any conclusion of its own. It is told today's date, that a later video supersedes an earlier one (a year-end roundup a mid-year one), to answer first and combine the excerpts, to go by the newest videos for what is current and say when an older one differs, to treat an excerpt as being about what its video's title names, to spell names as titles and descriptions do, to say in one sentence when the videos do not cover the question, and to cite[n]only and never write times. A follow-up is spelled out for it, and earlier answers reach it without their markers (they were numbered against other excerpts). Its answer is resolved before it is saved (knowledge/references.py): numbers it was not given are dropped, the rest renumbered in order of first use, each resolved to the caption line its sentence matches (an excerpt cited for two different moments becomes two references). Areferencesevent precedesdone; the expansion call's cost is added to the turn's.
The panel hides the model's raw numbers while streaming and renders the final markers as superscript links (AiMarkdown's cite hook) with a reference list (channel, title, year, timestamp, the caption line) folded behind an "N references" disclosure. Links open /watch/<id>?t= for a downloaded copy, else /watch?url=…&t=; the watch page reads t, keeps it through the stream-to-library redirect and seeks in place when that video is open.
Permissions¶
manage_ask (off by default) adds, changes, pauses, resumes and removes channels; everyone signed in lists channels and searches; use_ai chats and reads, lists and deletes their own threads. Members see a generic error instead of YouTube's text.
Sizes and limits¶
A 500-video channel of 25-minute videos is about 12,000 passages and about 45 MB (13 MB text, 10 MB FTS, 18 MB float16 vectors at 768 dimensions, a few MB of lines), copied by 7 nightly and 5 pre-migration backups. The vector cache keeps 8 channels. English captions only (the video's own: YouTube also offers every dubbed audio track's captions translated to English, which yt-dlp would pick and YouTube rate limits at once); videos without captions are listed but only their title and description are searchable.