mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-12-04 13:49:57 -05:00
ai: kind-generic search_files / get_file / read_content
Small models carry every tool definition on every request, and the
per-kind trios (four searches, three getters, three readers) cost a
quarter of an 8k context while giving the model near-duplicate choices.
Three generic endpoints replace them:
- POST files/search: one search over videos, archives, and docs with an
optional kind; channel (name or id), domain, author, subject each
imply their kind and are ignored for other kinds. When the term also
names channels/domains/authors, they are returned as `matches` so the
model can narrow without a second tool. Channels resolve by name, so
the library map already in the prompt is enough: no list call first.
- GET files/{id}: detail by id whatever the kind; videos now report
has_captions/has_comments and the full description, archives keep
their snapshot history.
- GET files/{id}/content?part=text|comments: captions, page text, or
comments, paged; a wrong part for the kind says what the file is.
Inventories take an optional slug on GET /inventories (one tool lists
and fetches). Listings are slimmed: no derivable captions/text links,
no size/mimetype, duration as H:MM:SS, published as a date. The
library map gains the tag names.
wrolpi_mcp keeps every existing tool name; the wrappers now call the
generic routes, and search_files/get_file/read_content are exposed too.
The old per-kind endpoints remain until the modes switch over.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
parent
0bc843d0ed
commit
12cd8355ad
10 changed files with 593 additions and 86 deletions
|
|
@ -57,7 +57,7 @@ async def test_ai_search_videos(async_client, test_session, video_factory):
|
|||
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'
|
||||
assert 'captions_link' not in result # derivable from the id; kept out of listings
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
|
@ -113,7 +113,7 @@ async def test_ai_search_archives(async_client, test_session, archive_factory):
|
|||
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'
|
||||
assert 'text_link' not in result # derivable from the id; kept out of listings
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
|
@ -519,3 +519,176 @@ def test_ai_format_download_error_tail():
|
|||
assert formatted['error'].endswith('ValueError: the real reason')
|
||||
assert len(formatted['error']) == DOWNLOAD_ERROR_LENGTH + 1
|
||||
assert 'error' not in _format_download(dict(id=2, url='https://example.com', status='new', error=None))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Consolidated, kind-generic endpoints for small models.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_ai_search_files_kinds(async_client, test_session, video_factory, archive_factory, channel_factory):
|
||||
"""One search covers every kind; kind narrows it; channel accepts a name or an id."""
|
||||
channel = channel_factory(name='Wild Cooking')
|
||||
video_factory(channel_id=channel.id, title='cooking rice')
|
||||
video_factory(title='cooking beans video')
|
||||
archive_factory(domain='cooking.example.com', title='cooking beans', contents='beans')
|
||||
test_session.commit()
|
||||
|
||||
async def search(**body):
|
||||
request, response = await async_client.post('/api/ai/files/search', content=json.dumps(body))
|
||||
assert response.status_code == HTTPStatus.OK, response.json
|
||||
return response.json
|
||||
|
||||
data = await search(search_str='cooking')
|
||||
assert data['total'] == 3
|
||||
assert {i['kind'] for i in data['results']} == {'video', 'archive'}
|
||||
# The matching channel and domain are offered so the model can narrow without another tool.
|
||||
assert [i['name'] for i in data['matches']['channels']] == ['Wild Cooking']
|
||||
assert data['matches']['channels'][0]['id'] == channel.id
|
||||
assert [i['name'] for i in data['matches']['domains']] == ['cooking.example.com']
|
||||
|
||||
data = await search(search_str='cooking', kind='video')
|
||||
assert data['total'] == 2 and all(i['kind'] == 'video' for i in data['results'])
|
||||
|
||||
data = await search(search_str='cooking', kind='archive')
|
||||
assert data['total'] == 1 and data['results'][0]['kind'] == 'archive'
|
||||
|
||||
# channel by exact name, partial name, and numeric id; channel implies kind=video.
|
||||
for channel_ref in ('Wild Cooking', 'wild', str(channel.id)):
|
||||
data = await search(search_str='cooking', channel=channel_ref)
|
||||
assert data['total'] == 1, channel_ref
|
||||
assert data['results'][0]['title'] == 'cooking rice'
|
||||
assert 'matches' not in data # already narrowed to one channel
|
||||
|
||||
# domain implies kind=archive.
|
||||
data = await search(domain='cooking.example.com')
|
||||
assert data['total'] == 1 and data['results'][0]['kind'] == 'archive'
|
||||
|
||||
# A filter that does not apply to the kind is ignored, not fatal.
|
||||
data = await search(search_str='cooking', kind='archive', channel='Wild Cooking')
|
||||
assert data['total'] == 1 and data['results'][0]['kind'] == 'archive'
|
||||
|
||||
# An unknown channel name gives no results and a hint, not an error.
|
||||
data = await search(search_str='cooking', channel='No Such Channel')
|
||||
assert data['total'] == 0 and data['results'] == []
|
||||
assert 'channel' in data['hint'].lower()
|
||||
|
||||
# Listings are slim: ids, titles, links, kind; no links the model can derive.
|
||||
result = data = (await search(search_str='cooking', kind='video'))['results'][0]
|
||||
assert {'id', 'kind', 'title', 'link'} <= set(result)
|
||||
assert 'captions_link' not in result and 'size' not in result and 'mimetype' not in result
|
||||
|
||||
# Something to search by is required.
|
||||
request, response = await async_client.post('/api/ai/files/search', content=json.dumps({}))
|
||||
assert response.status_code == HTTPStatus.OK # browse newest
|
||||
assert response.json['total'] == 3
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_ai_search_files_docs(async_client, test_session, test_directory, example_epub, refresh_files):
|
||||
"""kind=doc searches documents; author/subject imply kind=doc."""
|
||||
await refresh_files()
|
||||
request, response = await async_client.post('/api/ai/files/search', content=json.dumps(dict(search_str='WROLPi', kind='doc')))
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert response.json['total'] >= 1
|
||||
doc = response.json['results'][0]
|
||||
assert doc['kind'] == 'doc' and doc['link'] == f'/docs/{doc["id"]}'
|
||||
|
||||
# get_file returns the doc detail through the generic route.
|
||||
request, response = await async_client.get(f'/api/ai/files/{doc["id"]}')
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert response.json['kind'] == 'doc' and response.json['id'] == doc['id']
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_ai_get_file(async_client, test_session, video_factory, archive_factory, make_files_structure, tag_factory):
|
||||
"""get_file dispatches on the file's model and carries more than the listing row."""
|
||||
tag = await tag_factory('food')
|
||||
video = video_factory(title='wood stove install', with_caption_file=True)
|
||||
video.file_group.add_tag(test_session, tag.id)
|
||||
archive_factory(domain='example.com', url='https://example.com/a', title='first', contents='one')
|
||||
archive = archive_factory(domain='example.com', url='https://example.com/a', title='second', contents='two')
|
||||
test_session.commit()
|
||||
|
||||
request, response = await async_client.get(f'/api/ai/files/{video.file_group_id}')
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert response.json['kind'] == 'video'
|
||||
assert response.json['link'] == f'/videos/{video.file_group_id}'
|
||||
assert response.json['has_captions'] is True
|
||||
assert response.json['tags'] == ['food']
|
||||
assert response.json['mimetype'].startswith('video/')
|
||||
# Fetching does not mark the video viewed.
|
||||
test_session.expire_all()
|
||||
assert video.file_group.viewed is None
|
||||
|
||||
request, response = await async_client.get(f'/api/ai/files/{archive.file_group_id}')
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert response.json['kind'] == 'archive'
|
||||
assert response.json['url'] == 'https://example.com/a'
|
||||
assert [i['title'] for i in response.json['history']] == ['first']
|
||||
|
||||
# A plain file (no model) still resolves with a media link.
|
||||
from wrolpi.files.lib import upsert_file
|
||||
path, = make_files_structure({'photos/a.png': 'not really a png'})
|
||||
fg = await upsert_file(path)
|
||||
request, response = await async_client.get(f'/api/ai/files/{fg.id}')
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert response.json['link'] == '/media/photos/a.png'
|
||||
|
||||
request, response = await async_client.get('/api/ai/files/123456')
|
||||
assert response.status_code == HTTPStatus.NOT_FOUND
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_ai_read_content(async_client, test_session, video_factory, archive_factory):
|
||||
"""read_content serves captions/comments for videos and text for archives, paged."""
|
||||
info_json = dict(duration=5, comments=[dict(author='alice', text='great video')])
|
||||
video = video_factory(title='captioned', with_caption_file=True, with_info_json=info_json)
|
||||
contents = 'word ' * 2_000
|
||||
archive = archive_factory(domain='example.com', title='long read', contents=contents)
|
||||
test_session.commit()
|
||||
|
||||
request, response = await async_client.get(f'/api/ai/files/{video.file_group_id}/content')
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert response.json['content'].startswith('[00:00:0')
|
||||
|
||||
request, response = await async_client.get(f'/api/ai/files/{video.file_group_id}/content?part=comments')
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert 'alice: great video' in response.json['content']
|
||||
|
||||
request, response = await async_client.get(f'/api/ai/files/{archive.file_group_id}/content')
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert len(response.json['content']) == lib.PAGE_SIZE
|
||||
assert response.json['next_offset'] == lib.PAGE_SIZE
|
||||
request, response = await async_client.get(
|
||||
f'/api/ai/files/{archive.file_group_id}/content?offset={response.json["next_offset"]}')
|
||||
assert response.json['content'] == contents[lib.PAGE_SIZE:2 * lib.PAGE_SIZE]
|
||||
|
||||
# An archive has no comments; the error says what the file is.
|
||||
request, response = await async_client.get(f'/api/ai/files/{archive.file_group_id}/content?part=comments')
|
||||
assert response.status_code == HTTPStatus.NOT_FOUND
|
||||
assert 'archive' in response.json['error'].lower()
|
||||
|
||||
request, response = await async_client.get(f'/api/ai/files/{video.file_group_id}/content?part=bogus')
|
||||
assert response.status_code == HTTPStatus.BAD_REQUEST
|
||||
|
||||
request, response = await async_client.get('/api/ai/files/123456/content')
|
||||
assert response.status_code == HTTPStatus.NOT_FOUND
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_ai_get_inventory_optional_slug(async_client, food_inventory_factory):
|
||||
"""Without a slug the inventories are listed lean; with one, the inventory is returned in full."""
|
||||
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
|
||||
lean = next(i for i in response.json['results'] if i['slug'] == slug)
|
||||
assert lean['item_count'] == 1 and 'items' not in lean
|
||||
|
||||
request, response = await async_client.get(f'/api/ai/inventories?slug={slug}')
|
||||
assert response.status_code == HTTPStatus.OK
|
||||
assert response.json['inventory']['items'][0]['name'] == 'rice'
|
||||
|
||||
request, response = await async_client.get('/api/ai/inventories?slug=no-such-inventory')
|
||||
assert response.status_code == HTTPStatus.NOT_FOUND
|
||||
|
|
|
|||
|
|
@ -9,10 +9,11 @@ from modules.ai import context
|
|||
|
||||
@pytest.mark.asyncio
|
||||
async def test_build_library_context(async_client, test_session, video_factory, archive_factory,
|
||||
test_zim, food_inventory_factory):
|
||||
test_zim, food_inventory_factory, tag_factory):
|
||||
"""The map carries today's date, counts, and exact names."""
|
||||
from wrolpi.collections.models import Collection
|
||||
test_session.add(Collection(name='Talking Sasquach', kind='channel'))
|
||||
await tag_factory('Food Preservation')
|
||||
video_factory(title='a video')
|
||||
archive_factory(domain='example.com', title='a page', contents='contents')
|
||||
food_inventory_factory(name='Pantry')
|
||||
|
|
@ -25,6 +26,7 @@ async def test_build_library_context(async_client, test_session, video_factory,
|
|||
assert 'example.com' in text
|
||||
assert 'WROLPi example ZIM' in text
|
||||
assert 'Pantry' in text
|
||||
assert 'Tags (1): Food Preservation' in text
|
||||
assert 'user spellings may differ' in text
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -53,15 +53,21 @@ def test_format_file_group_video():
|
|||
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['duration'] == '1:07:01'
|
||||
assert result['published'] == '2024-01-02'
|
||||
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
|
||||
# Listings leave out what the model can derive or does not need to choose an item.
|
||||
assert 'captions_link' not in result and 'size' not in result and 'mimetype' not in result
|
||||
# Details add them back.
|
||||
detail = lib.format_file_group(fg, description_length=lib.DETAIL_DESCRIPTION_LENGTH, detail=True)
|
||||
assert detail['size'] == 1000 and detail['mimetype'] == 'video/mp4'
|
||||
assert len(detail['description']) == 500
|
||||
|
||||
|
||||
def test_format_file_group_archive():
|
||||
|
|
@ -69,7 +75,7 @@ def test_format_file_group_archive():
|
|||
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 'text_link' not in result
|
||||
# Listings omit the source URL so small models present the WROLPi link instead.
|
||||
assert 'url' not in result
|
||||
assert lib.format_file_group(fg, include_url=True)['url'] == 'https://example.com/a'
|
||||
|
|
@ -109,6 +115,17 @@ def test_html_to_text():
|
|||
assert 'evil' not in text and 'menu' not in text and '.x{}' not in text
|
||||
|
||||
|
||||
def test_format_duration_and_date():
|
||||
assert lib.format_duration(59) == '0:59'
|
||||
assert lib.format_duration(692) == '11:32'
|
||||
assert lib.format_duration(4021) == '1:07:01'
|
||||
assert lib.format_duration(None) is None and lib.format_duration('x') is None
|
||||
import datetime
|
||||
assert lib.format_date(datetime.datetime(2024, 1, 2, 13, 4, 5)) == '2024-01-02'
|
||||
assert lib.format_date('2024-01-02T13:04:05+00:00') == '2024-01-02'
|
||||
assert lib.format_date(None) is None
|
||||
|
||||
|
||||
def test_format_caption_chunks():
|
||||
chunks = [dict(start_seconds=0, text='hello'), dict(start_seconds=3671, text='goodbye')]
|
||||
text = lib.format_caption_chunks(chunks)
|
||||
|
|
|
|||
|
|
@ -19,6 +19,7 @@ EXPECTED_TOOLS = {
|
|||
'list_collections', 'list_zim_files', 'list_files',
|
||||
'get_statistics', 'get_inventory', 'get_inventory_items', 'get_status',
|
||||
'list_tags', 'search_suggestions', 'list_downloads', 'get_map_overview', 'search_places',
|
||||
'search_files', 'get_file', 'read_content',
|
||||
}
|
||||
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue