-
Notifications
You must be signed in to change notification settings - Fork 60
feat: Add "semble savings" command #76
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
21 commits
Select commit
Hold shift + click to select a range
1431444
Add semble stats command and saved token tracking
Pringled e529ae9
Merge branch 'main' of https://github.com/Pringled/semble into add-saβ¦
Pringled ac7c3b7
Improved semble savings
Pringled 7b18560
Pull main
Pringled 93ff6b6
Updated savings
Pringled 688533f
Update tests
Pringled 12963ab
Improve code quality
Pringled cdee40b
Move logic over to stats.py
Pringled 9e4d447
Improve code quality
Pringled 1e3ea12
Resolve conflicts
Pringled eec1374
Change error
Pringled 0b4034a
Update docs
Pringled 1d30641
Update docs
Pringled fdbcd0a
Simplify tests
Pringled 7a2b438
Update docs
Pringled 661dbbc
Rename functions and add CallType type
Pringled 5b52215
Only record savings when file_sizes are available
Pringled f3d935f
Update docstring:
Pringled 1737c4c
Update docstring:
Pringled e5024b7
Resolve comments
Pringled d94b8bf
Update docstring
Pringled File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,140 @@ | ||
| import json | ||
| import logging | ||
| from collections import defaultdict | ||
| from dataclasses import dataclass | ||
| from datetime import datetime, timedelta, timezone | ||
| from pathlib import Path | ||
|
|
||
| from semble.types import CallType, SearchResult | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
| _STATS_FILE = Path.home() / ".semble" / "savings.jsonl" | ||
|
|
||
|
|
||
| @dataclass | ||
| class BucketStats: | ||
| calls: int = 0 | ||
| snippet_chars: int = 0 | ||
| file_chars: int = 0 | ||
|
|
||
| def add(self, snippet_chars: int, file_chars: int) -> None: | ||
| """Update stats with a call and its character counts.""" | ||
| self.calls += 1 | ||
| self.snippet_chars += snippet_chars | ||
| self.file_chars += file_chars | ||
|
|
||
|
|
||
| @dataclass | ||
| class SavingsSummary: | ||
| buckets: dict[str, BucketStats] | ||
| call_type_counts: dict[str, int] | ||
|
|
||
|
|
||
| def save_search_stats( | ||
| results: list[SearchResult], | ||
| call_type: CallType, | ||
| file_sizes: dict[str, int], | ||
| ) -> None: | ||
| """Save stats about a search or find_related call to the stats file.""" | ||
| try: | ||
| snippet_chars = sum(len(result.chunk.content) for result in results) | ||
| file_chars = sum( | ||
| file_sizes[path] for path in {result.chunk.file_path for result in results} if path in file_sizes | ||
| ) | ||
|
|
||
| record = { | ||
| "ts": datetime.now(timezone.utc).timestamp(), | ||
| "call": call_type, | ||
| "results": len(results), | ||
| "snippet_chars": snippet_chars, | ||
| "file_chars": file_chars, | ||
| } | ||
| _STATS_FILE.parent.mkdir(parents=True, exist_ok=True) | ||
| with _STATS_FILE.open("a") as f: | ||
| f.write(json.dumps(record) + "\n") | ||
| except OSError: | ||
| pass | ||
|
|
||
|
|
||
| def build_savings_summary(path: Path = _STATS_FILE) -> SavingsSummary: | ||
| """Read savings.jsonl and return a SavingsSummary.""" | ||
| now = datetime.now(timezone.utc) | ||
| today = now.date() | ||
| seven_days_ago = (now - timedelta(days=7)).date() | ||
|
|
||
| buckets = { | ||
| "Today": BucketStats(), | ||
| "Last 7 days": BucketStats(), | ||
| "All time": BucketStats(), | ||
| } | ||
| call_type_counts: defaultdict[str, int] = defaultdict(int) | ||
|
|
||
| with path.open() as f: | ||
| for line in f: | ||
| try: | ||
| record = json.loads(line) | ||
| except json.JSONDecodeError: | ||
| logger.warning("Skipping malformed JSON line in stats file") | ||
| continue | ||
| snippet_chars = record["snippet_chars"] | ||
| file_chars = record["file_chars"] | ||
| call_type = record["call"] | ||
| call_type_counts[call_type] += 1 | ||
| dt = datetime.fromtimestamp(record["ts"], tz=timezone.utc) | ||
| in_today = dt.date() == today | ||
| in_last_7 = dt.date() > seven_days_ago | ||
| buckets["All time"].add(snippet_chars, file_chars) | ||
| if in_last_7: | ||
| buckets["Last 7 days"].add(snippet_chars, file_chars) | ||
| if in_today: | ||
| buckets["Today"].add(snippet_chars, file_chars) | ||
|
|
||
| return SavingsSummary(buckets=buckets, call_type_counts=dict(call_type_counts)) | ||
|
|
||
|
|
||
| def format_savings_report(path: Path | None = None, *, verbose: bool = False) -> str: | ||
| """Return a formatted token-savings report.""" | ||
| if path is None: | ||
| path = _STATS_FILE | ||
| if not path.exists(): | ||
| return "No stats yet. Run a search first." | ||
|
|
||
| summary = build_savings_summary(path) | ||
| bar_width = 16 | ||
| heavy_line = " " + "β" * 64 | ||
| light_line = " " + "β" * 64 | ||
|
|
||
| lines = [ | ||
| "", | ||
| " Semble Token Savings", | ||
| heavy_line, | ||
| f" {'Period':<12} {'Calls':<6} Savings", | ||
| light_line, | ||
| ] | ||
| for label, bucket in summary.buckets.items(): | ||
| saved_chars = max(0, bucket.file_chars - bucket.snippet_chars) | ||
| saved_tokens = saved_chars // 4 # standard ~4 chars/token approximation | ||
|
Pringled marked this conversation as resolved.
|
||
| if saved_tokens >= 1_000_000: | ||
| saved_str = f"~{saved_tokens / 1_000_000:.1f}M" | ||
| elif saved_tokens >= 1000: | ||
| saved_str = f"~{saved_tokens / 1000:.1f}k" | ||
| else: | ||
| saved_str = f"~{saved_tokens}" | ||
| calls_str = f"{bucket.calls / 1000:.1f}k" if bucket.calls >= 1000 else str(bucket.calls) | ||
| if bucket.file_chars > 0: | ||
| ratio = saved_chars / bucket.file_chars | ||
| filled = round(ratio * bar_width) | ||
| bar = "β" * filled + "β" * (bar_width - filled) | ||
| pct = round(ratio * 100) | ||
| lines.append(f" {label:<12} {calls_str:<6} [{bar}] {saved_str} tokens ({pct}%)") | ||
| else: | ||
| lines.append(f" {label:<12} {calls_str:<6} [{'β' * bar_width}] {saved_str} tokens") | ||
| if verbose and summary.call_type_counts: | ||
| lines += ["", " Usage Breakdown", light_line, f" {'Call type':<16} Calls"] | ||
| for call_type, count in sorted(summary.call_type_counts.items()): | ||
| count_str = f"{count / 1000:.1f}k" if count >= 1000 else str(count) | ||
| lines.append(f" {call_type:<16} {count_str}") | ||
| lines.append(heavy_line) | ||
| lines.append("") | ||
| return "\n".join(lines) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.