text
stringlengths
185
73.3k
repo
stringlengths
7
100
path
stringlengths
4
146
language
stringclasses
7 values
hash
stringlengths
16
16
score
float64
7
8.5
stars
int64
0
237k
"""Turning raw results into the comparison that matters. The headline question this answers: for each strategy, how much accuracy do you give up, and how much simulated money do you save, relative to sending everything to the top-tier model? """ from __future__ import annotations from collections import Counter from...
vbvansh/switchboard
eval/report.py
.py
ec194c6f79472d99
7
0
"""Runs task sets through routing strategies and records what happened. Design notes worth knowing: * Requests go straight to Ollama, not through the HTTP proxy. The proxy adds authentication and budgets, which are irrelevant here and would only make runs harder to start. The strategy objects being measured are t...
vbvansh/switchboard
eval/runner.py
.py
3753563cdddf8d27
7
0
"""Alembic environment. Two things here are not the Alembic defaults and both matter: 1. The database URL comes from Switchboard's settings, not alembic.ini, so there is one source of truth about which database is in use. 2. `render_as_batch=True`. SQLite cannot ALTER an existing column - it simply has no such...
vbvansh/switchboard
migrations/env.py
.py
d8293bba71d828c1
7
0
"""Record why the router chose a model. Revision ID: 0002 Revises: 0001 Created: 2026-08-24 Nullable on purpose: every row written before routing existed has no reason, and backfilling a guess would be worse than an honest blank. """ from __future__ import annotations from collections.abc import Sequence import sq...
vbvansh/switchboard
migrations/versions/20260824_0002_routing_reason.py
.py
e11edae3b7a0c47b
7
0
"""Per-user rate limit. Revision ID: 0003 Revises: 0002 Created: 2026-08-27 Nullable on purpose: NULL means "use the server default", so raising the default lifts everyone who has not been given a specific limit. Backfilling the current default into every row would freeze them at today's value. """ from __future__ i...
vbvansh/switchboard
migrations/versions/20260827_0003_rate_limit.py
.py
c98745d3837416cf
7
0
"""Record what routing would have done. Revision ID: 0004 Revises: 0003 Created: 2026-08-29 Both columns nullable. A request served before shadow mode existed carries no opinion, and inventing one - even "same as served" - would make every report that reads these columns wrong in a way nobody could see. """ from __f...
vbvansh/switchboard
migrations/versions/20260829_0004_shadow_mode.py
.py
1986e0c5b0901fd8
7
0
"""Download the LLMRouterBench archive. The dataset is NOT redistributed in this repository - it carries no explicit licence of its own, and its contents derive from 21+ upstream benchmarks with mixed terms plus outputs from commercial models. This script fetches it from the original source instead, so anyone reproduc...
vbvansh/switchboard
scripts/fetch_llmrouterbench.py
.py
e4e5ace3b75543cd
7
0
"""Response caching: never pay twice for the same question. The single biggest saving available to a gateway, and the simplest. If two requests are byte-for-byte identical, the answer already computed is the answer that would be computed again, so it is returned from memory for nothing. Four decisions shape this, and...
vbvansh/switchboard
switchboard/cache.py
.py
0739ff0f132a3240
7
0
"""Database connection and session management. SQLite is the right choice here: one file, no server, no setup, and Switchboard runs on a single machine. Going through SQLAlchemy rather than raw SQL keeps the door open to Postgres later without rewriting every query. """ from __future__ import annotations from collec...
vbvansh/switchboard
switchboard/ledger/db.py
.py
bf66df85481680be
7
0
"""API key generation and verification. Keys are hashed with a plain SHA-256, deliberately - not bcrypt or argon2. Those algorithms are slow *on purpose*, to make brute-forcing human-chosen passwords expensive. An API key here is 32 bytes of cryptographic randomness, so there is nothing to brute-force: guessing one i...
vbvansh/switchboard
switchboard/ledger/keys.py
.py
9dcac147a1036461
7
0
"""Numbers a monitoring system can scrape. Exposed in the Prometheus text format, which almost every monitoring tool reads. Written by hand rather than pulling in a client library: the format is about forty lines of string building, and this project already carries more runtime dependencies than it started with. The ...
vbvansh/switchboard
switchboard/metrics.py
.py
09fee137cdc2ba19
7
0
"""Stop hammering a provider that is clearly down. Retries handle a blip. A circuit breaker handles an outage. Without one, every request to a dead provider waits for its full timeout before failing over. If the timeout is 60 seconds and the provider has been down for an hour, every single request in that hour pays 6...
vbvansh/switchboard
switchboard/providers/breaker.py
.py
88e5b196b5277a16
7
0
"""Retrying provider calls that failed for a reason worth retrying. Network calls fail. A connection resets, a provider returns 503 while it restarts, a rate limit trips. Without retries every one of those is a failed request for a user, when waiting half a second would have worked. The care is in deciding WHAT to re...
vbvansh/switchboard
switchboard/providers/retry.py
.py
aa5380918649aa12
7
0
"""Per-user request rate limiting. Budgets stop someone spending too much over a month. They do nothing about someone spending it all in ninety seconds. A runaway retry loop in a script can burn a month's allowance before anyone notices, and hammer the provider hard enough to get the whole organisation rate-limited. ...
vbvansh/switchboard
switchboard/ratelimit.py
.py
5dae40fe95a6a705
7
0
"""Saving a trained router, and loading it back into the running server. Training happens offline against benchmark data; serving happens in a process that must start in under a second. So the trained thing is written to a file and loaded at startup. A note on the file format. It is a joblib pickle, which executes co...
vbvansh/switchboard
switchboard/routing/artifact.py
.py
7ffef1df9b1f0e47
7
0
"""The routing interface. Every strategy - the trivial baselines here, and the learned router in milestone 4 - implements `choose`. Keeping the interface this narrow is what makes the comparison fair: the evaluation harness swaps one object and changes nothing else about how a request is served. """ from __future__ i...
vbvansh/switchboard
switchboard/routing/base.py
.py
836ba6b17e686c50
7
0
"""Baseline strategies. These exist to make later results mean something. A learned router that beats nothing is not a result; a learned router that beats "always cheap", "always expensive", "pick at random" and "guess from keywords" is. `Random` in particular is the honest floor. Any strategy that cannot beat a coin...
vbvansh/switchboard
switchboard/routing/baselines.py
.py
57371bd5aa7aef2e
7
0
"""The router that actually serves traffic. Everything in `eval/` measures routing offline against recorded answers. This is the same decision made for real, against a live catalog of models, on a request that a person is waiting for. Three things separate it from the evaluation-side router: * **It maps names.** A r...
vbvansh/switchboard
switchboard/routing/live.py
.py
61b801e15853eea1
7
0
"""Schema version management. Wraps Alembic so the rest of the codebase never imports it directly, and so `switchboard db upgrade` and the startup check share one implementation. The rule this module exists to enforce: an application must never run against a database whose shape it does not recognise. Doing so does n...
vbvansh/switchboard
switchboard/schema.py
.py
0c6cc5e094463615
7
0
"""Shadow mode: measure what routing WOULD have done, without doing it. Nobody sensible points a new routing system at production traffic and hopes. So shadow mode runs the router on every request, records the model it would have chosen and what that would have cost - and then ignores the decision and serves the reque...
vbvansh/switchboard
switchboard/shadow.py
.py
24f4350268bbe3b2
7
0
"""Reading token usage out of a streaming response without disturbing it. A streamed answer arrives as Server-Sent Events: many small `data: {...}` lines. Two problems for the ledger: 1. Usage totals only appear in the final event, and only if the client asked for them (`stream_options.include_usage`). Switchboard...
vbvansh/switchboard
switchboard/streaming.py
.py
996fe1314e212d8d
7
0
"""Shared fixtures. Every test runs against an in-memory SQLite database and stubbed providers, so the suite needs neither Ollama running nor a file on disk. """ from __future__ import annotations import json import httpx import pytest from switchboard.catalog import ModelCatalog from switchboard.ledger import Dat...
vbvansh/switchboard
tests/conftest.py
.py
08becaf9eca0e5f7
7.5
0
import asyncio import os from logging.config import fileConfig from sqlalchemy import pool from sqlalchemy.engine import Connection from sqlalchemy.ext.asyncio import async_engine_from_config from alembic import context from application.core.database import Base from application.modules.users import models from appli...
Hesy47/Fast-Shop
alembic/env.py
.py
3dc8432213fd8304
7
0
"""OpenStack Emulator - A testing tool for OpenStack API clients.""" import argparse import importlib.metadata import os import sys from emulator.api.unified_app import SERVICE_PORTS, run_all_services, run_single_service try: __version__ = importlib.metadata.version("openstack-emulator") except importlib.metadat...
waldur/openstack-emulator
emulator/__init__.py
.py
12330d59dee25eb1
7
0
"""CloudKitty (rating) API endpoints for OpenStack emulator. Rating is what turns emulated compute and storage into the time-integrated consumption figures a billing client asks for. Rather than keep a separate ledger, dataframes are derived from the servers and volumes that already exist, so a scenario that provision...
waldur/openstack-emulator
emulator/api/cloudkitty.py
.py
56a5a069aebd4ec2
7
0
"""Embedded OpenID Provider for the OpenStack emulator. Keystone federation needs somewhere to get an access token from. Rather than require an external identity provider for every federation test, the emulator ships a minimal but real OpenID Provider: it publishes a discovery document and a JWKS, and issues RS256-sig...
waldur/openstack-emulator
emulator/api/oidc.py
.py
2fd732b45b4305bd
7
0
"""REST API for managing resource presets.""" from typing import Any import yaml # type: ignore[import-untyped] from fastapi import APIRouter, HTTPException from pydantic import BaseModel from emulator.core.database import db from emulator.core.presets import PresetLoader router = APIRouter(prefix="/presets", tags...
waldur/openstack-emulator
emulator/api/presets.py
.py
34676517325bd8ca
7
0
"""Unified OpenStack emulator application using single process with multiple ports.""" import asyncio import logging import os from typing import Dict import uvicorn from fastapi import APIRouter, FastAPI from emulator.api.cinder import router as cinder_router from emulator.api.cloudkitty import router as cloudkitty...
waldur/openstack-emulator
emulator/api/unified_app.py
.py
da09f4e29e7581fe
7
0
"""Common exception handlers for OpenStack emulator services.""" import logging import traceback from fastapi import FastAPI, Request from fastapi.responses import JSONResponse # fastapi.HTTPException subclasses this one, so handling the Starlette class # covers both application-raised errors and the router's own 40...
waldur/openstack-emulator
emulator/core/exceptions.py
.py
085ceaa8c68a0c7a
7
0
"""Keystone federation attribute mapping engine. Turns the claims an identity provider asserts about a user into a local Keystone identity, following the same algorithm as ``keystone.federation.utils``: * each rule's ``remote`` list is matched against the assertion; the first requirement whose attribute is missing ...
waldur/openstack-emulator
emulator/core/federation.py
.py
e98268d4c739dab2
7
0
"""OpenStack standard HTTP headers middleware.""" import uuid from fastapi import FastAPI, Request, Response from starlette.middleware.base import RequestResponseEndpoint def add_openstack_headers_middleware(app: FastAPI, service_name: str, api_version: str) -> None: """Add OpenStack standard headers to all res...
waldur/openstack-emulator
emulator/core/headers.py
.py
b9d67cb3f4846edd
7
0
"""Enhanced logging middleware for debugging requests and responses. Based on StackOverflow solution for proper response body capture. """ import json import logging import os from typing import cast from fastapi import FastAPI, Request, Response from starlette.background import BackgroundTask from starlette.middlew...
waldur/openstack-emulator
emulator/core/logging_middleware.py
.py
f5c2bcc94f180477
7
0
"""Middleware for scenario-based failure and load injection. Reads ``scenario_manager`` — the same instance the scenarios API and the status UI write to. All services share one process, so enabling a scenario on that singleton is immediately visible here with no synchronisation. """ import asyncio from fastapi impor...
waldur/openstack-emulator
emulator/core/middleware.py
.py
386498351264946b
7
0
"""Scenario manager for controlling failure and load injection. This module provides centralized scenario management with cross-process state sharing via file-based persistence. """ import random import threading import time from dataclasses import dataclass from datetime import datetime, timezone from typing import ...
waldur/openstack-emulator
emulator/core/scenario_manager.py
.py
ef67285c57bb98df
7
0
"""Simplified authentication for single-process emulator.""" import logging from dataclasses import dataclass from typing import Any from fastapi import HTTPException logger = logging.getLogger(__name__) @dataclass class TokenInfo: """Information extracted from a validated token.""" project_id: str pr...
waldur/openstack-emulator
emulator/core/simple_auth.py
.py
bf5f7775ff308b60
7
0
#!/usr/bin/env python3 """ OpenAPI Specification Comparison Tool Compares OpenStack reference specifications with emulator implementations to generate detailed compliance reports. """ import json import sys from pathlib import Path from typing import Any, Dict, List, Set import yaml def load_spec(file_path: str) -...
waldur/openstack-emulator
scripts/compare_apis.py
.py
729d29b45c051418
7
0
#!/usr/bin/env python3 """Generate structured changelog data from git history between two refs. Collects commits between two git refs, categorizes them by type (feature, fix, refactor, chore, docs, other), and outputs JSON suitable for changelog generation. Usage: python scripts/generate_changelog_data.py <new_re...
waldur/openstack-emulator
scripts/generate_changelog_data.py
.py
c33470f4448d8213
7
0
#!/usr/bin/env python3 """Release management script for OpenStack Emulator. Manages releases by: - Updating the version in both pyproject.toml and charts/openstack-emulator/Chart.yaml - Running local pre-release checks (Python lint + type-check, Helm chart lint + unit tests) - Creating and (optionally) pushing a git t...
waldur/openstack-emulator
scripts/release.py
.py
0a765d90e70067db
7
0
"""Shared test helpers. Keystone refuses to mint a scoped token for a user that holds no role on the target scope (``TokenModel._validate_project_scope``), and the emulator reproduces that. A test that wants a project-scoped token therefore has to grant the role first, the same bootstrap an operator performs with ``op...
waldur/openstack-emulator
tests/conftest.py
.py
f8284bf924b56a1b
7.5
0
"""Pytest fixtures for SDK tests against the OpenStack emulator.""" import socket import threading import time from typing import Generator import openstack import pytest import uvicorn from openstack.connection import Connection from emulator.core.database import db def find_free_port() -> int: """Find a free...
waldur/openstack-emulator
tests/sdk/conftest.py
.py
ab7cde45bb0fd12f
7.5
0
"""SDK tests for OIDC-federated Keystone authentication against the emulator. These drive the real keystoneauth ``v3oidcpassword`` / ``v3oidcaccesstoken`` plugins end to end: fetch the provider's discovery document, exchange a password grant for an access token, present it to Keystone's OS-FEDERATION auth endpoint, an...
waldur/openstack-emulator
tests/sdk/test_sdk_federation.py
.py
082cdb45aff78a5b
7.5
0
"""SDK tests for Keystone Identity service.""" from openstack.connection import Connection class TestKeystoneAuthentication: """Test Keystone authentication via SDK.""" def test_connection_authorized(self, openstack_connection: Connection) -> None: """Test that SDK connection is properly authenticat...
waldur/openstack-emulator
tests/sdk/test_sdk_keystone.py
.py
100dee2931c73ed8
7.5
0
"""SDK tests for the Placement service.""" from openstack.connection import Connection from emulator.core.database import db class TestPlacementResourceProviders: def test_list_resource_providers(self, openstack_connection: Connection) -> None: providers = list(openstack_connection.placement.resource_pr...
waldur/openstack-emulator
tests/sdk/test_sdk_placement.py
.py
45a7a946f8051871
7.5
0
"""End-to-end scenario over the waldur-site-agent preset, driven by openstacksdk. This is the scenario the emulator's federation and quota work exists to support: an out-of-process agent provisions a tenant with per-volume-type and object storage quotas, and a user it pre-created then signs in through an identity prov...
waldur/openstack-emulator
tests/sdk/test_sdk_preset_scenario.py
.py
a39d573129520407
7.5
0
"""Application configuration. All configuration is loaded from environment variables (optionally from a `.env` file placed in the backend directory). No secrets are hardcoded here. """ import os from pathlib import Path from dotenv import load_dotenv BASE_DIR = Path(__file__).resolve().parent.parent load_dotenv(BAS...
shi-YangYang/openlab
backend/app/config.py
.py
545c861a6917e9bb
7
0
"""PDF download and background job execution.""" import asyncio import re from pathlib import Path from typing import Any, Awaitable, Callable, Dict, List, Optional import httpx from . import database from .config import settings from .llm_config import get_http_proxy from .platforms import LoginExpiredError, LoginRe...
shi-YangYang/openlab
backend/app/downloader.py
.py
16b45fbd4cce2246
7
0
"""LLM configuration persistence and resolution. The LLM configuration is stored as a list of "groups" in a local JSON file (default ``backend/data/llm_config.json``). Each group describes one OpenAI-compatible endpoint (``base_url`` / ``api_key`` / ``models`` / ``default_model``), and ``active_group`` marks which one...
shi-YangYang/openlab
backend/app/llm_config.py
.py
14153c52ee52659e
7
0
"""PDF text extraction via PyMuPDF. Reuses the PDF files downloaded by spec-001 (stored under ``settings.papers_dir``). Extraction failures (missing file, corrupt PDF, scanned/empty text) are surfaced as :class:`PdfExtractionError` so callers can mark the analysis as ``failed`` with a clear reason. """ from pathlib im...
shi-YangYang/openlab
backend/app/pdf.py
.py
eb03783f99c5d13e
7
0
"""Browser helpers for login flow and logged-in search. Browser automation is blocking IO, so every function here is synchronous and intended to run inside a worker thread (``threading`` / ``asyncio.to_thread``) rather than on the FastAPI event loop. ``playwright.sync_api`` is imported lazily so that the backend still...
shi-YangYang/openlab
backend/app/platforms/browser.py
.py
588a8edd3a62adeb
7
0
"""Login-state storage and platform status management. Login states are Playwright ``storage_state`` JSON blobs stored under ``data/platform_sessions/<platform>.json``. ``data/`` is gitignored (NFR-2), so no cookies ever enter version control. The in-memory status machine mirrors the four states agreed in the spec:: ...
shi-YangYang/openlab
backend/app/platforms/sessions.py
.py
b8efa6d320633d6e
7
0
"""Aggregate multiple search providers concurrently. Each provider runs independently via ``asyncio.gather``. Failures never break the whole search: a failing provider contributes a ``fallback`` entry (its external search-page URL) while the others contribute ``papers``. """ import asyncio from typing import Any, Dict...
shi-YangYang/openlab
backend/app/search/aggregator.py
.py
d6901f408342931b
7
0
"""Search provider abstraction. Every provider normalizes results into a common paper structure so the aggregator (and downstream API) only has to deal with one shape:: { "source": str, "arxiv_id": str, "title": str, "authors": [str], "abstract": str, "categories": ...
shi-YangYang/openlab
backend/app/search/base.py
.py
0ead97d64340f99b
7
0
import os import re from pathlib import Path from groq import Groq from dotenv import load_dotenv load_dotenv() # Phrases Whisper emits on pure background noise or end credits HALLUCINATION_EXACT_MATCHES = [ "thank you for watching", "thanks for watching", "subtitles by", "subscribe to th...
Aditya-C-Patil/AI-Video-Assistant
core/transcriber.py
.py
ed22db625f0a899d
7
0
import os import glob import tempfile from typing import List import yt_dlp from pydub import AudioSegment import shutil DOWNLOAD_DIR = "downloads" os.makedirs(DOWNLOAD_DIR, exist_ok=True) def cleanup_audio_chunks(chunks_dir: str = "downloads"): """Removes all intermediate audio chunk files after transcription.""...
Aditya-C-Patil/AI-Video-Assistant
utils/audio_processor.py
.py
84e156aea32e2934
7
0
#!/usr/bin/env python3 """i18n compression-quality eval (zh/ja/ko): does extractive compression keep the answer-bearing content in CJK? No LLM/API calls -- fully local. Part C -- our own DETERMINISTIC needle answer-retention (zh/ja/ko): the always- runs regression gate. A distinctive needle sentence is buried (in the...
6TcbpVB4h7jSZWz2/headroomlabs-ai__headroom
benchmarks/i18n_compression_eval.py
.py
335520ad714e826c
7
0
#!/usr/bin/env python3 """CLI runner for Headroom benchmark suite. This script provides a convenient interface for running benchmarks and generating reports. It wraps pytest-benchmark with Headroom-specific options and markdown report generation. Usage: # Run all benchmarks python benchmarks/run_benchmarks.py...
6TcbpVB4h7jSZWz2/headroomlabs-ai__headroom
benchmarks/run_benchmarks.py
.py
af5c36fd8c6e13d2
7
0
"""Conversation generators for benchmark scenarios. This module provides generators for realistic conversation patterns that exercise Headroom transforms: - Agentic conversations: Multi-turn with tool calls (SmartCrusher) - RAG conversations: Large context injection (CacheAligner) These generators produce conversati...
6TcbpVB4h7jSZWz2/headroomlabs-ai__headroom
benchmarks/scenarios/conversations.py
.py
896919d285794e67
7
0
"""Data generators for tool output benchmarks. This module provides realistic data generators that simulate common tool output patterns encountered in agentic workflows: - Search results: Elasticsearch/vector search responses with scores - Log entries: Structured logs with timestamps and severity levels - API respons...
6TcbpVB4h7jSZWz2/headroomlabs-ai__headroom
benchmarks/scenarios/tool_outputs.py
.py
5382bf5e40a41ebe
7
0
#!/usr/bin/env python3 """Cache reconstruction cost: cache_creation on first turn after idle gap vs in-window. Prints a pretty distribution table plus a final cost-comparison summary across three caching strategies: current (5m default), naive flip to 1h, and conditional 1h-after-idle. """ import json from collection...
6TcbpVB4h7jSZWz2/headroomlabs-ai__headroom
claude_analysis_ttl.py
.py
887ff8cda4072525
7
0
#!/usr/bin/env -S uv run --script # /// script # requires-python = ">=3.11" # dependencies = [] # /// """Validates a candidate worker-agent name before the main agent runs `herdr agent start` (see skills/dispatching-work/references/dispatch-mechanics.md and plan-mechanics.md). Checks the two things a hand-done check t...
wayne930242/straw-boss
scripts/check-agent-name.py
.py
79c4743a3e6fa7b9
7.3
3
#!/usr/bin/env -S uv run --script # /// script # requires-python = ">=3.11" # dependencies = [] # /// """Claude Stop hook: require a dispatched session to report before stopping.""" from __future__ import annotations import json import sys from pathlib import Path from typing import Any from dispatch_state import ( ...
wayne930242/straw-boss
scripts/dispatched-agent-stop-guard.py
.py
b8ce18814d7784a2
7.3
3
#!/usr/bin/env -S uv run --script # /// script # requires-python = ">=3.11" # dependencies = [] # /// """SessionStart hook: primes a candidate main-agent session with the i-am-orchestrator skill's own operating stance, guaranteed rather than left to the model choosing to invoke that skill itself. Skipped for a dispatc...
wayne930242/straw-boss
scripts/orchestrator-priming.py
.py
adddb3558e5e3529
7.3
3
#!/usr/bin/env -S uv run --script # /// script # requires-python = ">=3.11" # dependencies = [] # /// """Targeted reads of a plan's state -- never dumps everything by default. See skills/dispatching-work/references/plan-mechanics.md. Prefer the narrowest query that answers the actual question: --task for one task, --n...
wayne930242/straw-boss
scripts/read-plan-status.py
.py
ce0243c5ec530387
7.3
3
#!/usr/bin/env -S uv run --script # /// script # requires-python = ">=3.11" # dependencies = [] # /// """Resolve a dispatched agent's `awaiting-main-agent` checkpoint: deliver the main agent's reply and record the resolution, atomically. See skills/dispatching-work/references/plan-mechanics.md's "Main-agent- action ch...
wayne930242/straw-boss
scripts/reply-to-worker.py
.py
51cd45beadf2fdf5
7.3
3
#!/usr/bin/env -S uv run --script # /// script # requires-python = ">=3.11" # dependencies = [] # /// """Appends a timestamped progress note to a dispatch's own progress log. Callable by a dispatched agent at any point during its work, any number of times -- not just at a terminal state or checkpoint. Writes to a sibl...
wayne930242/straw-boss
scripts/report-progress.py
.py
36d6c16ceb44bae7
7.3
3
#!/usr/bin/env -S uv run --script # /// script # requires-python = ">=3.11" # dependencies = [] # /// """Emit one JSON event for every persisted Plan status transition. Unlike the old shell polling loop, this watcher deduplicates by complete file content rather than filename. A checkpoint file that is later overwritte...
wayne930242/straw-boss
scripts/watch-plan-status.py
.py
630148ca69c405e5
7.3
3
#!/usr/bin/env -S uv run --script # /// script # requires-python = ">=3.11" # dependencies = [] # /// """Archives a finished dispatch instruction and syncs plan.json. See skills/dispatching-work/references/dispatch-mechanics.md (instruction lifecycle) and references/plan-mechanics.md (plan status). This script only mo...
wayne930242/straw-boss
scripts/wrap-up-task.py
.py
38453ba62af7b172
7.3
3
#!/usr/bin/env python3 # /// script # requires-python = ">=3.9" # dependencies = [] # /// """Merge the hand-curated broker definitions with the scraped Optery directory into a single data/brokers.json registry. Curated entries win on every field. Optery-only entries land as priority-1 stubs with no opt-out URL yet, re...
leakydata/broker-remove
scripts/build_registry.py
.py
270518c874f2ae54
7
0
#!/usr/bin/env python3 # /// script # requires-python = ">=3.9" # dependencies = [] # /// """Harvest structured broker facts from Optery's public data-broker directory. Each directory page exposes a labelled table — opt-out URL, privacy contact email, home country, broker type. That turns ~950 registry stubs into entr...
leakydata/broker-remove
scripts/enrich_from_optery.py
.py
6e26595d15c0f0bd
7
0
#!/usr/bin/env python3 # /// script # requires-python = ">=3.9" # dependencies = [] # /// """Generate statutory opt-out / deletion request emails. Why this exists: most brokers put their CAPTCHA on the web form, but state privacy law obliges them to honor a written request sent to their privacy address. Email has no C...
leakydata/broker-remove
scripts/make_optout_email.py
.py
548fe6e41e63ecee
7
0
#!/usr/bin/env python3 # /// script # requires-python = ">=3.9" # dependencies = [] # /// """Generate a protected-person removal request for current or former law enforcement officers, judges, and public officials. Several brokers (PeopleConnect, LexisNexis, Whitepages) run a protected-person track that is broader and...
leakydata/broker-remove
scripts/make_protected_person_request.py
.py
a1c51ed2854fb60c
7
0
#!/usr/bin/env python3 # /// script # requires-python = ">=3.9" # dependencies = [] # /// """Find corporate families by shared mail infrastructure. The domain-based family scan (family_scan.py) groups brokers whose registered contact addresses share a domain. That finds the obvious cases and misses the interesting one...
leakydata/broker-remove
scripts/mx_family_scan.py
.py
a05632215d60b39c
7
0
"""Where the read-only reference data ends up, and where *your* data goes. This project is installed as a Claude Code plugin, which means the two halves of it live in different places and must never be confused: ROOT the plugin itself -- the broker registry, the playbooks, the knowledge files...
leakydata/broker-remove
scripts/paths.py
.py
04a29c2be1b586fc
7
0
#!/usr/bin/env python3 # /// script # requires-python = ">=3.9" # dependencies = [] # /// """Produce the next batch of statutory removal emails to send. Sending is deliberately paced. A personal mailbox tops out around 500 recipients a day, and a sudden burst of near-identical messages is what spam heuristics look for...
leakydata/broker-remove
scripts/queue_batch.py
.py
b8d0bc3fbf8c7a65
7
0
#!/usr/bin/env python3 # /// script # requires-python = ">=3.9" # dependencies = [] # /// """Decide what to send next, across two competing queues. There are two backlogs and they are not interchangeable: NEW brokers -- never contacted. Each letter opens a whole unexplored holding, but th...
leakydata/broker-remove
scripts/send_plan.py
.py
e6863901a9ae1195
7
0
""" OpenClaw 运行时配置映射 将 L1 抽象配置映射到 OpenClaw 原生配置路径 """ from typing import Any, Dict, Optional from .adapter import adapter # 配置映射表:L1 抽象路径 → OpenClaw 原生配置路径 CONFIG_MAPPING: Dict[str, str] = { "agent_loop.max_tokens": "agents.defaults.model.contextWindow", "agent_loop.compaction_model": "agents.defaults.compact...
RenLimin/openclaw-v5.0
adapters/openclaw/config.py
.py
a98f8408dc1afdd5
7
0
""" OpenClaw 运行时健康检查 实现 L1 契约的健康检查能力 """ from typing import Any, Dict, List, Tuple from .adapter import OpenClawAdapter, HealthStatus def check_all_components(adapter: OpenClawAdapter) -> Tuple[str, List[Dict[str, Any]]]: """检查所有核心组件的健康状态""" all_results: List[Dict[str, Any]] = [] overall_status = "ok" ...
RenLimin/openclaw-v5.0
adapters/openclaw/health.py
.py
fc899ed9759f5add
7
0
""" OpenClaw 运行时适配器 — L1 最小能力契约的 OpenClaw 实现 将 L1 抽象接口翻译为 OpenClaw 运行时 API 调用。 符合 ADR-012:Agent 运行时作为可变因素。 移植性保证: - 此文件是唯一与 OpenClaw 耦合的代码 - OpenClaw 升级只影响此文件内部实现 - L2-L4 通过 RuntimeAdapter 抽象接口调用,不感知 OpenClaw """ from typing import Any, Dict, List, Optional, Tuple import json import subprocess import glob import shu...
RenLimin/openclaw-v5.0
adapters/openclaw/openclaw_adapter.py
.py
9825c3ded84c3135
7
0
#!/usr/bin/env python3 """用量追踪:从 provider API 获取用量信息,写入 config/usage.json。 设计约束: - 只读访问 openclaw.json(获取 provider 配置) - 外部文件 config/usage.json 存储用量状态 - 各 provider 用量 API 不同,需分别适配 - 支持 --dry-run 预览 """ import argparse import json import subprocess import sys import urllib.request import urllib.error from datet...
RenLimin/openclaw-v5.0
model-scheduling/scripts/fetch_usage.py
.py
a05277918055c2fc
7
0
#!/usr/bin/env python3 """网络健康探测:检测各 provider 的可用性和延迟。 设计约束: - 只读访问 openclaw.json - 外部文件 config/usage.json 更新健康状态 - 轻量探测(发送最小请求,不消耗大量 token) - 支持 --dry-run 预览 """ import argparse import json import subprocess import sys import time import urllib.request from datetime import datetime, timezone from pathlib imp...
RenLimin/openclaw-v5.0
model-scheduling/scripts/health_check.py
.py
398864e8d7a18165
7
0
#!/usr/bin/env python3 """智能路由引擎:根据任务类型、用量、健康状态选择最优模型。 设计约束: - 只读访问 openclaw.json - 读 config/models.yaml + config/routing.yaml + config/usage.json - 输出推荐模型,不直接切换(切换由 cron 或 sessions.patch 执行) - 支持 --dry-run 预览路由决策 """ import argparse import json import subprocess import sys from pathlib import Path REPO_ROOT...
RenLimin/openclaw-v5.0
model-scheduling/scripts/router.py
.py
1e33bb59196cd23b
7
0
#!/usr/bin/env python3 """模型注册表同步:从 openclaw.json 读取已有 provider/models,写入 config/models.yaml。 设计约束: - 只读访问 openclaw.json(通过 `openclaw config get`),绝不写入 - 外部文件 config/models.yaml 是 model-scheduling 的主来源 - 支持 --dry-run 预览,默认先 dry-run 再确认执行 """ import argparse import json import subprocess import sys from pathlib ...
RenLimin/openclaw-v5.0
model-scheduling/scripts/sync_models.py
.py
61b45691ebe25bd5
7
0
"""数据库连接管理。 提供线程安全的 SQLite 连接,启用 WAL 模式和外键约束。 """ from __future__ import annotations import sqlite3 from pathlib import Path from threading import local DATA_DIR = Path.home() / ".openclaw" / "data" DB_PATH = DATA_DIR / "platform.db" _thread_local = local() def get_connection() -> sqlite3.Connection: """获取当前线...
RenLimin/openclaw-v5.0
persistence/connection.py
.py
74a922eb694b99af
7
0
"""Schema 迁移引擎。 版本号 + 迁移脚本模式。按版本顺序执行,幂等设计。 """ from __future__ import annotations import importlib from pathlib import Path from persistence.connection import get_connection SCHEMA_TABLE = """ CREATE TABLE IF NOT EXISTS _schema_version ( version INTEGER PRIMARY KEY, applied_at TEXT NOT NULL ) """ def get_...
RenLimin/openclaw-v5.0
persistence/migration.py
.py
9cd488838feb6acd
7
0
"""Repository 基类。 提供通用的 CRUD 操作,子类只需定义 table_name。 """ from __future__ import annotations from typing import Any, Optional from persistence.connection import get_connection class Repository: """业务仓储基类。""" table_name: str def _conn(self): return get_connection() def _execute(self, sql: st...
RenLimin/openclaw-v5.0
persistence/repository.py
.py
e21f3cd7dfa98662
7
0
#!/usr/bin/env python3 """Recursive credential-shape scanner. NEVER prints secret values.""" import json, os, re, sys, hashlib KEY_PAT = re.compile( r'(secret|token|key|password|passwd|pwd|apikey|credential|cred|auth|bearer|' r'cookie|session|signature|sign|corpid|corpsecret|appid|appsecret|dsn|' r'connect...
RenLimin/openclaw-v5.0
scripts/cred_scan.py
.py
e79414dc19706282
7
0
#!/usr/bin/env python3 """文档格式转换:PDF/Word/Excel → Markdown(知识库单一来源格式) 用法: python3 scripts/document_processing/convert.py <input_file> [output_file] 示例: python3 scripts/document_processing/convert.py report.pdf report.md python3 scripts/document_processing/convert.py data.xlsx data.md python3 scripts/d...
RenLimin/openclaw-v5.0
scripts/document_processing/convert.py
.py
3066458cd3b73e89
7
0
#!/usr/bin/env python3 """图片 OCR 文字识别 用法: python3 scripts/document_processing/ocr.py <image_file> [--lang chi_sim+eng] 示例: python3 scripts/document_processing/ocr.py screenshot.png python3 scripts/document_processing/ocr.py scan.jpg --lang chi_sim+eng """ import sys import subprocess from pathlib import ...
RenLimin/openclaw-v5.0
scripts/document_processing/ocr.py
.py
fd8b047f79dbd625
7
0
""" 结构化日志实现 (Layer 1) 遵循 OpenTelemetry GenAI semantic conventions """ import os import json import logging from datetime import datetime from typing import Any, Dict, Optional # 日志根目录 LOG_ROOT = "/Users/bangcle/.openclaw/workspace/logs/observability" ERROR_LOG_ROOT = os.path.join(LOG_ROOT, "errors") # 敏感字段列表(需要 reda...
RenLimin/openclaw-v5.0
scripts/observability/logging.py
.py
6467f90269ae77d9
7
0
#!/usr/bin/env python3 """L2 记忆语义检索监控 — ADR-009 决策 4 落地实现 背景(2026-08-24 实测教训): `openclaw memory status --index` 会**报告健康而检索实际停摆**。 当天 status 显示 provider=local / 393 chunks / Embeddings: ready / dims=768 全部正常, 但 memory_search 实际返回 disabled:true + "index sources changed",一条都不返回。 ⇒ **status 不可信,必须实查(behavioral pro...
RenLimin/openclaw-v5.0
scripts/observability/memory_search_monitor.py
.py
c1f0dc8662f44927
7
0
""" 追踪实现 (Layer 2) 步骤级 span / 因果链 / trace replay """ import uuid import threading from typing import Any, Dict, List, Optional, Tuple from dataclasses import dataclass, field from datetime import datetime from .logging import log_event @dataclass class Span: span_id: str name: str start_time: datetime ...
RenLimin/openclaw-v5.0
scripts/observability/tracing.py
.py
146562d599b0029d
7
0
#!/usr/bin/env python3 """OCR Engine — 文字识别核心模块 三级 OCR 能力: L1: tesseract(快速,已安装) L2: RapidOCR(高精度,中文优先) L3: 预留云端接口 """ import subprocess import sys from pathlib import Path def ocr_rapid(image_path: str, lang: str = 'ch') -> str: """L2: RapidOCR(推荐,中文精度高)""" from rapidocr_onnxruntime import RapidOCR ...
RenLimin/openclaw-v5.0
scripts/ocr_engine/ocr.py
.py
af1feaa83de57887
7
0
#!/usr/bin/env python3 """PDF 批量 OCR — 将扫描版 PDF 转为 Markdown 用法: python3 scripts/ocr_engine/pdf_ocr.py input.pdf --output output.md python3 scripts/ocr_engine/pdf_ocr.py input.pdf --pages 1-10 """ import subprocess import sys from pathlib import Path def render_pdf_to_images(pdf_path: str, output_dir: str, pa...
RenLimin/openclaw-v5.0
scripts/ocr_engine/pdf_ocr.py
.py
7d40f5719e79797e
7
0
"""智能体日志:记录每次 AI 调用的提示词 / 思维链(reasoning_content)/ 用量等。 - 独立日志文件:`data/logs/agent-<启动时间戳>.log`(JSON 行,UTF-8),保留最近 20 个; - 与 `lantai-*.log`(应用/访问日志)分离:本 logger 不向 root 传播; - 图片内容(base64)不入日志,替换为字节数占位。 """ from __future__ import annotations import json import logging from datetime import datetime from typing import Any,...
awardat/lantai
backend/app/agent_log.py
.py
8341fe45b20c30c3
7
0
"""文本切块:段落感知 + 长度窗口(默认 400 字符/块,重叠 50 字符)。""" from __future__ import annotations import re from . import config _SPACE_RE = re.compile(r"[ \t\r\f\v]+") _BLANK_LINE_RE = re.compile(r"\n\s*\n") # 中日韩统一表意文字/扩展区/兼容区(含假名时排除——仅汉字之间删空格, # 假名/英文单词间距保留;0.1.38 CH-073 方案 A) _CJK_GAP_RE = re.compile( r"([\u3400-\u4dbf\u4e00...
awardat/lantai
backend/app/chunker.py
.py
cc44e40a5330c755
7
0
"""兰台全局配置:路径、版本、常量。 所有路径基于运行形态解析: - 源码运行(uvicorn):BASE_DIR = backend/ - PyInstaller 冻结运行:BASE_DIR = 可执行文件所在目录 """ from __future__ import annotations import sys from pathlib import Path APP_VERSION = "0.1.43" APP_NAME = "lantai" def _base_dir() -> Path: if getattr(sys, "frozen", False): return Path(sys....
awardat/lantai
backend/app/config.py
.py
fcdb98a139094c89
7
0
"""Embedding 调用:OpenAI 兼容 embeddings 端点(Ollama 走 /v1)。 注意:DeepSeek 官方 API 无 embeddings 接口;云端请选 OpenAI/通义等支持 embeddings 的服务,或 embedding 使用本地 Ollama(如 bge-m3)。 """ from __future__ import annotations import httpx import numpy as np from . import config from .llm import _friendly_error, normalize_base_url from .schemas ...
awardat/lantai
backend/app/embeddings.py
.py
568f1ab712983c71
7
0
"""兰台(lantai)FastAPI 应用入口。 - 纯 API:/api/*(docs / chat / settings) - 前端托管:/ 挂载 frontend/(原生单页,无构建) - 统一响应:{code, message, data};错误 message 为中文 """ from __future__ import annotations import logging from contextlib import asynccontextmanager from fastapi import FastAPI, HTTPException, Request from fastapi.exceptions im...
awardat/lantai
backend/app/main.py
.py
8336e22f80ece65b
7
0
"""解析管线:文件类型路由 → 文本提取 → 切块 → 向量化 → 入库。 - 文字文档 / Office / 文字 PDF:本地解析(无需 LLM); - 图片:调用该类型配置的视觉模型生成内容描述; - 图片 PDF(扫描件):逐页提取内嵌图片 → OCR 模型识别。 """ from __future__ import annotations from pathlib import Path from . import chunker, config, embeddings, filetype, llm, store as store_mod from .store import Store def _vision...
awardat/lantai
backend/app/pipeline.py
.py
1492020a63c1f89a
7
0
"""检索器:问题向量化 → 向量库 top-k 检索(0.1.39 起 hybrid + rerank + 降级)。 流水线(对外接口 retrieve() 不变,业务调用无感): 1. 向量召回 top-K(embedding 故障时自动降级 BM25 关键词检索); 2. BM25 召回 top-K(FTS5 + 中文 bigram); 3. RRF(倒数排名融合)合并两路候选 → top-k(R107); 4. rerank(R106,设置页「重排」开启时):交叉编码器精排 → top-k。 """ from __future__ import annotations import logging from . imp...
awardat/lantai
backend/app/retriever.py
.py
614f1b1e3854b7f1
7
0