|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import argparse |
| 4 | +from datetime import UTC, datetime, timedelta |
| 5 | +from typing import TYPE_CHECKING |
| 6 | + |
| 7 | +from context_use.cli import output as out |
| 8 | +from context_use.cli.base import ApiCommand, create_batch_reporter, run_batches |
| 9 | +from context_use.cli.config import Config |
| 10 | + |
| 11 | +if TYPE_CHECKING: |
| 12 | + from context_use import ContextUse |
| 13 | + |
| 14 | + |
| 15 | +class EmbedCommand(ApiCommand): |
| 16 | + name = "embed" |
| 17 | + help = "Embed thread content for semantic search" |
| 18 | + description = ( |
| 19 | + "Generate vector embeddings for all unprocessed threads. " |
| 20 | + "Asset threads require descriptions first (run 'describe' beforehand). " |
| 21 | + "Use --last-days or --since to limit the date range." |
| 22 | + ) |
| 23 | + llm_mode = "batch" |
| 24 | + |
| 25 | + def add_arguments(self, parser: argparse.ArgumentParser) -> None: |
| 26 | + parser.add_argument( |
| 27 | + "--last-days", |
| 28 | + type=int, |
| 29 | + default=None, |
| 30 | + help="Only process threads from the last N days", |
| 31 | + ) |
| 32 | + parser.add_argument( |
| 33 | + "--since", |
| 34 | + type=str, |
| 35 | + default=None, |
| 36 | + help="Only process threads after this date (YYYY-MM-DD)", |
| 37 | + ) |
| 38 | + |
| 39 | + async def run( |
| 40 | + self, |
| 41 | + cfg: Config, |
| 42 | + ctx: ContextUse, |
| 43 | + args: argparse.Namespace, |
| 44 | + ) -> None: |
| 45 | + since = self._resolve_since(args) |
| 46 | + |
| 47 | + out.header("Embedding threads") |
| 48 | + out.info("Embeds all threads that have not been embedded yet.") |
| 49 | + if since: |
| 50 | + out.kv("Since", since.strftime("%Y-%m-%d")) |
| 51 | + print() |
| 52 | + |
| 53 | + batches = await ctx.create_thread_embedding_batches(since=since) |
| 54 | + |
| 55 | + if not batches: |
| 56 | + out.info("No threads to embed.") |
| 57 | + return |
| 58 | + |
| 59 | + await run_batches( |
| 60 | + ctx, |
| 61 | + batches, |
| 62 | + reporter_factory=create_batch_reporter, |
| 63 | + ) |
| 64 | + |
| 65 | + out.success("Thread embeddings generated") |
| 66 | + out.kv("Batches", len(batches)) |
| 67 | + print() |
| 68 | + |
| 69 | + def _resolve_since(self, args: argparse.Namespace) -> datetime | None: |
| 70 | + if args.since: |
| 71 | + return datetime.fromisoformat(args.since).replace(tzinfo=UTC) |
| 72 | + if args.last_days is not None: |
| 73 | + return datetime.now(UTC) - timedelta(days=args.last_days) |
| 74 | + return None |
0 commit comments