ai: add the /api/ai blueprint, the read-only LLM tool catalog

Lean, flat, LLM-shaped read-only endpoints over the library: global,
video, archive, and doc search; paged captions, archive text, and zim
entries; collections, inventories, and a media-directory text reader.
Links are server-computed; big content is paged, never truncated.
This ports the formatting layer from wrolpi_mcp (untouched for now)
into tested code.  First phase of ai.md.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Roland 2026-08-25 21:03:11 -06:00
parent bcd12c9b96
commit 06dae71ad0
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
10 changed files with 1046 additions and 0 deletions

View file

267
modules/ai/test/test_api.py Normal file
View file

@ -0,0 +1,267 @@
"""Tests for the /api/ai blueprint — the LLM tool catalog."""
import json
from http import HTTPStatus
import pytest
from modules.ai import lib
@pytest.mark.asyncio
async def test_ai_search_all(async_client, test_session, video_factory, archive_factory):
"""Global search returns lean results of every kind with links and a total."""
video_factory(title='canning tomatoes')
archive_factory(domain='example.com', title='canning peppers', contents='all about canning peppers')
test_session.commit()
request, response = await async_client.post('/api/ai/search', content=json.dumps(dict(search_str='canning')))
assert response.status_code == HTTPStatus.OK
assert response.json['total'] == 2
kinds = {i['kind'] for i in response.json['results']}
assert kinds == {'video', 'archive'}
for result in response.json['results']:
assert result['link']
assert result['id']
@pytest.mark.asyncio
async def test_ai_search_all_limit(async_client, test_session, archive_factory):
"""The limit is clamped and the total reports all matches so the model narrows, not pages."""
for i in range(3):
archive_factory(domain='example.com', title=f'gardening {i}', contents='gardening guide')
test_session.commit()
content = dict(search_str='gardening', limit=1)
request, response = await async_client.post('/api/ai/search', content=json.dumps(content))
assert response.status_code == HTTPStatus.OK
assert len(response.json['results']) == 1
assert response.json['total'] == 3
# An excessive limit is clamped to the maximum.
content = dict(search_str='gardening', limit=10_000)
request, response = await async_client.post('/api/ai/search', content=json.dumps(content))
assert response.status_code == HTTPStatus.OK
@pytest.mark.asyncio
async def test_ai_search_videos(async_client, test_session, video_factory):
"""Video search returns lean video results with captions links."""
video_factory(title='sourdough starter', with_caption_file=True)
video_factory(title='unrelated')
test_session.commit()
content = dict(search_str='sourdough')
request, response = await async_client.post('/api/ai/videos/search', content=json.dumps(content))
assert response.status_code == HTTPStatus.OK
assert response.json['total'] == 1
result = response.json['results'][0]
assert result['kind'] == 'video'
assert result['link'] == f'/videos/{result["id"]}'
assert result['captions_link'] == f'/api/ai/videos/{result["id"]}/captions'
@pytest.mark.asyncio
async def test_ai_get_video(async_client, test_session, video_factory):
"""A single video can be fetched by its FileGroup ID."""
video = video_factory(title='wood stove install')
test_session.commit()
file_group_id = video.file_group_id
request, response = await async_client.get(f'/api/ai/videos/{file_group_id}')
assert response.status_code == HTTPStatus.OK
assert response.json['id'] == file_group_id
assert response.json['kind'] == 'video'
assert response.json['link'] == f'/videos/{file_group_id}'
# Fetching does not mark the video viewed.
test_session.expire_all()
assert video.file_group.viewed is None
request, response = await async_client.get('/api/ai/videos/123456')
assert response.status_code == HTTPStatus.NOT_FOUND
@pytest.mark.asyncio
async def test_ai_get_video_captions(async_client, test_session, video_factory):
"""Captions are returned as timestamped, paged text."""
video = video_factory(title='captioned', with_caption_file=True)
test_session.commit()
request, response = await async_client.get(f'/api/ai/videos/{video.file_group_id}/captions')
assert response.status_code == HTTPStatus.OK
assert response.json['content'].startswith('[00:00:0')
assert response.json['total_chars'] > 0
# An offset beyond the end returns an empty page, never an error.
offset = response.json['total_chars'] + 100
request, response = await async_client.get(f'/api/ai/videos/{video.file_group_id}/captions?offset={offset}')
assert response.status_code == HTTPStatus.OK
assert response.json['content'] == ''
assert response.json['next_offset'] is None
@pytest.mark.asyncio
async def test_ai_search_archives(async_client, test_session, archive_factory):
"""Archive search supports the domain filter and returns text links."""
archive_factory(domain='example.com', title='pressure canning', contents='pressure canning guide')
archive_factory(domain='other.org', title='water bath canning', contents='water bath canning guide')
test_session.commit()
content = dict(search_str='canning', domain='example.com')
request, response = await async_client.post('/api/ai/archives/search', content=json.dumps(content))
assert response.status_code == HTTPStatus.OK
assert response.json['total'] == 1
result = response.json['results'][0]
assert result['kind'] == 'archive'
assert result['text_link'] == f'/api/ai/archives/{result["id"]}/text'
@pytest.mark.asyncio
async def test_ai_get_archive_text(async_client, test_session, archive_factory):
"""Archive text is served from the readability text file and paged."""
contents = 'word ' * 2_000 # 10,000 chars, more than two pages.
archive = archive_factory(domain='example.com', title='long read', contents=contents)
test_session.commit()
file_group_id = archive.file_group_id
request, response = await async_client.get(f'/api/ai/archives/{file_group_id}/text')
assert response.status_code == HTTPStatus.OK
assert len(response.json['content']) == lib.PAGE_SIZE
assert response.json['next_offset'] == lib.PAGE_SIZE
assert response.json['total_chars'] == len(contents)
# The second page continues where the first ended.
request, response = await async_client.get(
f'/api/ai/archives/{file_group_id}/text?offset={response.json["next_offset"]}')
assert response.status_code == HTTPStatus.OK
assert response.json['content'] == contents[lib.PAGE_SIZE:2 * lib.PAGE_SIZE]
request, response = await async_client.get('/api/ai/archives/123456/text')
assert response.status_code == HTTPStatus.NOT_FOUND
@pytest.mark.asyncio
async def test_ai_search_docs(async_client, test_session, test_directory, example_epub, refresh_files):
"""Docs can be searched and fetched with links."""
await refresh_files()
content = dict(search_str='WROLPi')
request, response = await async_client.post('/api/ai/docs/search', content=json.dumps(content))
assert response.status_code == HTTPStatus.OK
assert response.json['total'] >= 1
result = response.json['results'][0]
assert result['kind'] == 'doc'
assert result['link'] == f'/docs/{result["id"]}'
request, response = await async_client.get(f'/api/ai/docs/{result["id"]}')
assert response.status_code == HTTPStatus.OK
assert response.json['id'] == result['id']
assert response.json['kind'] == 'doc'
@pytest.mark.asyncio
async def test_ai_zims(async_client, test_session, test_zim):
"""Zims can be listed, searched, and their entries read as paged text."""
request, response = await async_client.get('/api/ai/zims')
assert response.status_code == HTTPStatus.OK
assert response.json['total'] == 1
zim_id = response.json['results'][0]['id']
# Search one specific Zim.
content = dict(search_str='item', zim_id=zim_id)
request, response = await async_client.post('/api/ai/zims/search', content=json.dumps(content))
assert response.status_code == HTTPStatus.OK
assert response.json['total'] >= 1
result = response.json['results'][0]
assert result['zim_id'] == zim_id
assert result['link'] == f'/api/zim/{zim_id}/entry/{result["path"]}'
# An empty search is a clear error for the model.
request, response = await async_client.post('/api/ai/zims/search', content=json.dumps(dict()))
assert response.status_code == HTTPStatus.BAD_REQUEST
# Read the entry the search found.
request, response = await async_client.get(f'/api/ai/zims/{zim_id}/entry?path={result["path"]}')
assert response.status_code == HTTPStatus.OK
assert response.json['content']
assert response.json['link'] == f'/api/zim/{zim_id}/entry/{result["path"]}'
# The path is required.
request, response = await async_client.get(f'/api/ai/zims/{zim_id}/entry')
assert response.status_code == HTTPStatus.BAD_REQUEST
@pytest.mark.asyncio
async def test_ai_list_collections(async_client, test_session, archive_factory):
"""Collections can be listed and filtered by kind."""
archive_factory(domain='example.com', title='a page', contents='contents')
test_session.commit()
request, response = await async_client.get('/api/ai/collections?kind=domain')
assert response.status_code == HTTPStatus.OK
assert response.json['total'] == 1
assert response.json['results'][0]['name'] == 'example.com'
assert response.json['results'][0]['kind'] == 'domain'
request, response = await async_client.get('/api/ai/collections?kind=channel')
assert response.status_code == HTTPStatus.OK
assert response.json['total'] == 0
@pytest.mark.asyncio
async def test_ai_inventories(async_client, food_inventory_factory):
"""Inventories are listed lean, and fetched in full by slug."""
slug = food_inventory_factory(items=[dict(name='rice', count=2)])
request, response = await async_client.get('/api/ai/inventories')
assert response.status_code == HTTPStatus.OK
assert response.json['total'] >= 1
lean = next(i for i in response.json['results'] if i['slug'] == slug)
assert lean['item_count'] == 1
assert 'items' not in lean
request, response = await async_client.get(f'/api/ai/inventories/{slug}')
assert response.status_code == HTTPStatus.OK
assert response.json['inventory']['items'][0]['name'] == 'rice'
request, response = await async_client.get('/api/ai/inventories/no-such-inventory')
assert response.status_code == HTTPStatus.NOT_FOUND
@pytest.mark.asyncio
async def test_ai_read_file(async_client, test_directory):
"""Text files in the media directory can be read; everything else is refused."""
(test_directory / 'notes').mkdir()
(test_directory / 'notes/todo.txt').write_text('buy more rice\n' * 400) # > one page
request, response = await async_client.get('/api/ai/files/read?path=notes/todo.txt')
assert response.status_code == HTTPStatus.OK
assert response.json['content'].startswith('buy more rice')
assert response.json['next_offset'] == lib.PAGE_SIZE
# Missing path parameter.
request, response = await async_client.get('/api/ai/files/read')
assert response.status_code == HTTPStatus.BAD_REQUEST
# Missing file.
request, response = await async_client.get('/api/ai/files/read?path=notes/nope.txt')
assert response.status_code == HTTPStatus.NOT_FOUND
# Binary files are refused.
(test_directory / 'notes/blob.bin').write_bytes(b'\x00\x01\x02')
request, response = await async_client.get('/api/ai/files/read?path=notes/blob.bin')
assert response.status_code == HTTPStatus.BAD_REQUEST
@pytest.mark.asyncio
async def test_ai_read_file_refuses_escapes(async_client, test_directory):
"""Reads outside the media directory, and of config files, are refused."""
# Path traversal.
request, response = await async_client.get('/api/ai/files/read?path=../secrets.txt')
assert response.status_code == HTTPStatus.BAD_REQUEST
# The config directory can contain secrets.
(test_directory / 'config').mkdir(exist_ok=True)
(test_directory / 'config/wrolpi.yaml').write_text('secret: hunter2')
request, response = await async_client.get('/api/ai/files/read?path=config/wrolpi.yaml')
assert response.status_code == HTTPStatus.BAD_REQUEST

130
modules/ai/test/test_lib.py Normal file
View file

@ -0,0 +1,130 @@
"""Tests for the /api/ai formatting helpers."""
from modules.ai import lib
def test_wrolpi_link_video():
fg = dict(id=123, model='video', video=dict(), mimetype='video/mp4')
assert lib.wrolpi_link(fg) == '/videos/123'
def test_wrolpi_link_doc():
fg = dict(id=5, model='doc', mimetype='application/pdf')
assert lib.wrolpi_link(fg) == '/docs/5'
def test_wrolpi_link_archive():
fg = dict(id=7, model='archive', mimetype='text/html')
assert lib.wrolpi_link(fg) == '/archives/7'
def test_wrolpi_link_epub(test_directory):
fg = dict(id=9, mimetype='application/epub+zip', primary_path=test_directory / 'books/foo.epub')
assert lib.wrolpi_link(fg) == '/epub/epub.html?url=/download/books/foo.epub'
def test_wrolpi_link_mobi(test_directory):
fg = dict(id=9, mimetype='application/x-mobipocket-ebook', primary_path=test_directory / 'books/foo.mobi')
assert lib.wrolpi_link(fg) == '/download/books/foo.mobi'
def test_wrolpi_link_media_fallback(test_directory):
fg = dict(id=2, mimetype='image/png', primary_path=test_directory / 'photos/a.png')
assert lib.wrolpi_link(fg) == '/media/photos/a.png'
def test_wrolpi_link_no_path():
assert lib.wrolpi_link(dict(mimetype='image/png')) is None
def test_format_file_group_video():
fg = dict(
id=42,
model='video',
title='Canning Basics',
mimetype='video/mp4',
size=1000,
length=4021,
published_datetime='2024-01-02',
tags=['food'],
video=dict(channel=dict(id=1, name='Homesteading'), description='x' * 500),
d_headline='pressure <b>canning</b>',
)
result = lib.format_file_group(fg)
assert result['id'] == 42
assert result['kind'] == 'video'
assert result['link'] == '/videos/42'
assert result['captions_link'] == '/api/ai/videos/42/captions'
assert result['channel'] == 'Homesteading'
assert result['duration'] == 4021
assert result['headline'] == 'pressure <b>canning</b>'
assert result['tags'] == ['food']
# Listing descriptions are truncated.
assert len(result['description']) == lib.LISTING_DESCRIPTION_LENGTH + 1
# Empty fields are omitted.
assert 'author' not in result and 'url' not in result
def test_format_file_group_archive():
fg = dict(id=8, model='archive', title='Some Page', mimetype='text/html', url='https://example.com/a')
result = lib.format_file_group(fg)
assert result['kind'] == 'archive'
assert result['link'] == '/archives/8'
assert result['text_link'] == '/api/ai/archives/8/text'
assert result['url'] == 'https://example.com/a'
def test_format_file_groups_total():
result = lib.format_file_groups([dict(id=1, model='archive')], 55)
assert result['total'] == 55
assert len(result['results']) == 1
def test_paginate_text():
text = 'a' * (lib.PAGE_SIZE + 100)
page = lib.paginate_text(text, 0)
assert len(page['content']) == lib.PAGE_SIZE
assert page['next_offset'] == lib.PAGE_SIZE
assert page['total_chars'] == lib.PAGE_SIZE + 100
page = lib.paginate_text(text, page['next_offset'])
assert len(page['content']) == 100
assert page['next_offset'] is None
# Exact boundary has no next page.
page = lib.paginate_text('a' * lib.PAGE_SIZE, 0)
assert page['next_offset'] is None
# Empty text.
page = lib.paginate_text(None, 0)
assert page == dict(content='', next_offset=None, total_chars=0)
def test_html_to_text():
html = '<html><head><style>.x{}</style><script>evil()</script></head>' \
'<body><nav>menu</nav><p>Hello</p><p></p><p>World</p></body></html>'
text = lib.html_to_text(html)
assert 'Hello' in text and 'World' in text
assert 'evil' not in text and 'menu' not in text and '.x{}' not in text
def test_format_caption_chunks():
chunks = [dict(start_seconds=0, text='hello'), dict(start_seconds=3671, text='goodbye')]
text = lib.format_caption_chunks(chunks)
assert text == '[00:00:00] hello\n[01:01:11] goodbye'
assert lib.format_caption_chunks(None) == ''
def test_format_zim_search():
zim_results = [dict(
metadata=dict(title='Test Zim'),
estimate=2,
search=[
dict(zim_id=1, path='one', title='One', headline='the first', rank=1),
dict(zim_id=1, path='two', title='Two', headline=None, rank=1),
],
)]
result = lib.format_zim_search(zim_results)
assert result['total'] == 2
assert result['results'][0]['link'] == '/api/zim/1/entry/one'
assert result['results'][0]['zim'] == 'Test Zim'
assert 'headline' not in result['results'][1]