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
"""multipart/form-data encoding for Discord file attachments. No boto3 dependency, unlike defer.py, since it's used on the direct (non-deferred) response path too and must stay cheap to import there. """ import json import mimetypes import uuid def build_multipart_body(payload, files): """Encode a Discord messa...
borhara/cordless
src/cordless/_multipart.py
.py
d3854ee10e4fe195
7.54
11
"""Minimal terminal spinner, no external dependencies.""" import sys import threading import time _FRAMES = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏" _GREEN = "\033[32m" _RED = "\033[31m" _YELLOW = "\033[33m" _DIM = "\033[2m" _BOLD = "\033[1m" _RESET = "\033[0m" _ERASE_LINE = "\033[K" _tty = sys.stdout.isatty() # Set by callers (e.g. --verbose...
borhara/cordless
src/cordless/_progress.py
.py
b95e2e54b80edd6f
7.54
11
import base64 import json from ._multipart import build_multipart_body from .errors import MessageTooLongError from .models import Attachment, Channel, Guild, Member, Message, Role, User, _wrap _CHANNEL_MESSAGE_WITH_SOURCE = 4 _UPDATE_MESSAGE = 7 _DEFERRED_CHANNEL_MESSAGE_WITH_SOURCE = 5 _DEFERRED_UPDATE_MESSAGE = 6 ...
borhara/cordless
src/cordless/context.py
.py
5783d06d043e655c
7.54
11
"""Deferred interaction support: async Lambda invoke and Discord followup webhook.""" import json import threading import time from http.client import HTTPException, HTTPSConnection _TIMEOUT = 10 # Kept open across invocations in a warm Lambda container, so most requests # skip the TLS handshake instead of paying fo...
borhara/cordless
src/cordless/defer.py
.py
494bced51c76a6da
7.54
11
"""Discord embed builder.""" class EmbedField: """What `Embed.add_field` creates; you rarely construct it directly.""" def __init__(self, name, value, inline=False): self.name = name self.value = value self.inline = inline def to_dict(self): d = {"name": self.name, "value...
borhara/cordless
src/cordless/embeds.py
.py
1980c6988cbe20a6
7.54
11
# bit values from Discord's permissions flags docs. new bits get added # there occasionally, check against the current docs before adding one. _PERMISSION_BITS = { "create_instant_invite": 0x1, "kick_members": 0x2, "ban_members": 0x4, "administrator": 0x8, "manage_channels": 0x10, "manage_guild"...
borhara/cordless
src/cordless/models.py
.py
b4d186bdd7e5dc24
7.54
11
"""Optional cross-invocation coordination for outbound Discord rate limits. Enabled by setting `ratelimit = true` in [deploy] (cordless.toml), which provisions a DynamoDB table and points CORDLESS_RATELIMIT_TABLE at it in the deployed function's environment. Header state from Discord's responses is cached locally per ...
borhara/cordless
src/cordless/ratelimit.py
.py
3526f15eb09001d2
7.54
11
import base64 import json import urllib.error import urllib.parse import urllib.request API_BASE = "https://discord.com/api/v10" # Discord's API sits behind Cloudflare, which blocks urllib's default # "Python-urllib/x.y" User-Agent outright (403, error code 1010) regardless # of whether the credentials are valid. Any...
borhara/cordless
src/cordless/register.py
.py
5d30ba50ab47ecb8
7.54
11
import asyncio import inspect from .errors import ( CordlessError, NoResponseError, UnknownButtonError, UnknownCommandError, UnknownComponentError, UnknownModalError, UnsupportedInteractionError, ) PING = 1 APPLICATION_COMMAND = 2 MESSAGE_COMPONENT = 3 APPLICATION_COMMAND_AUTOCOMPLETE = 4 ...
borhara/cordless
src/cordless/router.py
.py
66258876367c4b56
7.54
11
"""Test helpers for cordless bots: build interaction payloads and dispatch them through the real router - the same code path a deployed bot runs on - without a live Discord round-trip or HTTP signature verification. Import the module and use it as a namespace, e.g.: from cordless import testing response, ctx...
borhara/cordless
src/cordless/testing.py
.py
ebf1c151c6562360
8.04
11
import importlib.util import os import tempfile import zipfile _LAMBDA_RUNTIMES = ["python3.10", "python3.11", "python3.12", "python3.13", "python3.14"] # Local-machine-only tooling (the `cordless deploy`/`cordless dev` CLI itself) # that never runs inside a deployed Lambda - excluded from both the layer and # bundle...
borhara/cordless
src/cordless/upload.py
.py
f5ab98124ad73f5f
7.54
11
"""Discord webhook execution: send/edit/delete messages via a webhook id+token. Unlike send_message/edit_message in app.py, none of this needs DISCORD_BOT_TOKEN - a webhook's id+token pair is its own credential. Kept dependency-free (stdlib HTTPSConnection, like defer.py) so it stays cheap to import on the direct resp...
borhara/cordless
src/cordless/webhook.py
.py
5abecaa37b443a08
7.54
11
"""Worker Lambda entrypoint for deferred interactions (async Lambda invoke).""" import asyncio import traceback from .context import Context def make_worker_handler(bot): """Return a Lambda handler that processes deferred interactions invoked asynchronously.""" def handler(event, lambda_context=None): ...
borhara/cordless
src/cordless/worker.py
.py
772da14c8edfd9da
7.54
11
"""EPPI-specific data models extending the core models.""" import re from collections.abc import Callable from datetime import UTC, datetime from enum import StrEnum from typing import Any from destiny_sdk.enhancements import EnhancementFileInput, EnhancementType, Visibility from destiny_sdk.parsers import EPPIParser...
destiny-evidence/data-extraction-evaluation-toolkit
deet/data_models/eppi.py
.py
b482b574e8df4fe2
7.48
8
"""Data models to help with evaluation.""" import csv from pathlib import Path from typing import Literal from loguru import logger from pydantic import BaseModel from deet.data_models.base import Attribute class AttributeMetric(BaseModel): """Data structure storing a metric for an attribute for a data extract...
destiny-evidence/data-extraction-evaluation-toolkit
deet/data_models/evaluation.py
.py
d75f346c118d4c84
7.48
8
"""Data models for LLM extraction outputs.""" from datetime import UTC, datetime from enum import StrEnum from typing import Any, Final, Self from pydantic import BaseModel, Field, model_validator from deet.data_models.base import GoldStandardAnnotation from deet.data_models.documents import GoldStandardAnnotatedDoc...
destiny-evidence/data-extraction-evaluation-toolkit
deet/data_models/extraction.py
.py
1be36faa58b5e5ab
7.48
8
"""Models to employ for implementing DEET jobs in sequential, harmonised _pipelines_.""" import os import shutil import subprocess import traceback from abc import ABC, abstractmethod from collections.abc import Callable from enum import StrEnum, auto from pathlib import Path from typing import Any, Literal, TypeVar, ...
destiny-evidence/data-extraction-evaluation-toolkit
deet/data_models/pipeline.py
.py
a1eb0eda40be4aec
7.48
8
"""Data models for procesed annotation data.""" import csv from collections.abc import Sequence from pathlib import Path from typing import Any, Literal from loguru import logger from pydantic import BaseModel from deet.data_models.base import ( DEFAULT_ATTRIBUTE_TYPE, AnnotationType, Attribute, Attr...
destiny-evidence/data-extraction-evaluation-toolkit
deet/data_models/processed_gold_standard_annotations.py
.py
098215d825a2f503
7.48
8
""" Data models for DeetProject. DeetProjects handle the one-time definition of configuration options, and create standardised directory structures to store resources like prompt csvs, link maps, experiment results. """ from __future__ import annotations from dataclasses import dataclass from datetime import UTC, da...
destiny-evidence/data-extraction-evaluation-toolkit
deet/data_models/project.py
.py
ed8ae282634e3019
7.48
8
"""Metric functions and registries for gold-vs-LLM evaluation.""" from collections.abc import Callable, Sequence from functools import partial from typing import Any import numpy as np from pydantic import BaseModel, Field from rapidfuzz.distance import Levenshtein from sklearn.metrics import ( # type:ignore[import-...
destiny-evidence/data-extraction-evaluation-toolkit
deet/evaluators/metrics.py
.py
2af8590820d86a33
7.48
8
"""Generic classes and functions for converters.""" import json from abc import ABC, abstractmethod from enum import StrEnum, auto from pathlib import Path from loguru import logger from pydantic import TypeAdapter from deet.data_models.base import Attribute, AttributeType from deet.data_models.documents import ( ...
destiny-evidence/data-extraction-evaluation-toolkit
deet/processors/base_converter.py
.py
aa952e2e7c248c91
7.48
8
""" A register of supported supported annotation formats and a map to their converters. """ from __future__ import annotations from enum import StrEnum, auto from typing import TYPE_CHECKING if TYPE_CHECKING: from deet.processors.base_converter import AnnotationConverter SUPPORTED_EXTENSIONS: set[str] = {".csv"...
destiny-evidence/data-extraction-evaluation-toolkit
deet/processors/converter_register.py
.py
9382d4b7826e4b19
7.48
8
"""Parse raw EPPI citation markup into page and highlight fields.""" import re from dataclasses import dataclass from deet.data_models.eppi import EppiItemAttributeFullTextDetails from deet.utils.text_normalisation import clean_extracted_text # ``Page 7:`` (case-insensitive); captures the page number. _PAGE_PATTERN ...
destiny-evidence/data-extraction-evaluation-toolkit
deet/processors/eppi_citation_parser.py
.py
a48cd95063ca4702
7.48
8
"""Utilities for parsing input files (e.g. pdf) into output files (e.g. md).""" import json from abc import ABC, abstractmethod from datetime import UTC, datetime from enum import StrEnum, auto from io import StringIO from os import PathLike from pathlib import Path from typing import Literal import pypandoc from dis...
destiny-evidence/data-extraction-evaluation-toolkit
deet/processors/parser.py
.py
ea183589e8bb4c52
7.48
8
# ruff: noqa: PLC0415 """A CLI app to run deet pipelines.""" import contextlib import warnings import typer from deet.logger import logger from deet.scripts.commands import experiments, project from deet.scripts.commands.deprecated import ( export_config_template_legacy, extract_data_legacy, init_linkage...
destiny-evidence/data-extraction-evaluation-toolkit
deet/scripts/cli.py
.py
0a29ac2035080508
7.48
8
# ruff: noqa: PLC0415 """Sub-commands for project initialisation and configuration.""" from pathlib import Path from typing import TYPE_CHECKING, Annotated if TYPE_CHECKING: from deet.data_models.project import DeetProject import typer from InquirerPy import inquirer from deet.processors.converter_register imp...
destiny-evidence/data-extraction-evaluation-toolkit
deet/scripts/commands/project.py
.py
59bd4624073f926d
7.48
8
# ruff: noqa: PLC0415 """CLI helpers for the ``deet project`` setup/creation commands.""" from pathlib import Path from typing import TYPE_CHECKING, Annotated if TYPE_CHECKING: from deet.data_models.project import DeetProject import typer from InquirerPy import inquirer from pydantic import BaseModel, Validation...
destiny-evidence/data-extraction-evaluation-toolkit
deet/scripts/project_utils.py
.py
209ee79d4e47330f
7.48
8
"""decorators to handle typer context in commands.""" from __future__ import annotations from dataclasses import dataclass from functools import wraps from typing import TYPE_CHECKING, ParamSpec, TypeVar, cast import typer if TYPE_CHECKING: from collections.abc import Callable from deet.data_models.project...
destiny-evidence/data-extraction-evaluation-toolkit
deet/scripts/typer_context.py
.py
26942042e9908841
7.48
8
"""App settings using pydantic-settings.""" from enum import StrEnum, auto from functools import lru_cache from pathlib import Path from typing import Annotated from dotenv import set_key from pydantic import Field, SecretStr from pydantic_settings import BaseSettings, SettingsConfigDict from deet.data_models.ui_sch...
destiny-evidence/data-extraction-evaluation-toolkit
deet/settings.py
.py
c703f9157bfe5ca8
7.48
8
"""Interface to pass messages to UI(s).""" from typing import NoReturn import typer from deet.logger import logger from deet.settings import LogLevel from deet.ui.terminal import render_to_console def notify(message: str, level: LogLevel = LogLevel.INFO) -> None: """Send messages to logger and to UIs (currentl...
destiny-evidence/data-extraction-evaluation-toolkit
deet/ui/messenger.py
.py
59bd041ce9f97e95
7.48
8
"""Rich UI components for the terminal.""" from rich import box from rich.align import Align from rich.console import RenderableType from rich.markdown import Markdown from rich.panel import Panel def info_panel(content: str, title: str = "INFO") -> Panel: """Return a styled box for displaying Markdown content."...
destiny-evidence/data-extraction-evaluation-toolkit
deet/ui/terminal/components.py
.py
181195617d2517a3
7.48
8
"""Single import for the rich console, and methods to write to it.""" import re import textwrap from collections.abc import Generator, Iterable, Iterator from contextlib import contextmanager from inspect import cleandoc from jinja2 import Environment, PackageLoader, select_autoescape from rich.console import Console...
destiny-evidence/data-extraction-evaluation-toolkit
deet/ui/terminal/render.py
.py
e5d7e1e7225db93c
7.48
8
"""Module containing interactive wizards for collecting information for the deet cli.""" from abc import ABC, abstractmethod from enum import Enum from pathlib import Path from typing import Any, Final, cast, get_args from InquirerPy import inquirer from InquirerPy.base import BaseSimplePrompt from prompt_toolkit.key...
destiny-evidence/data-extraction-evaluation-toolkit
deet/ui/terminal/wizards.py
.py
fd862ba0e29421a3
7.48
8
"""Action Hint guidance: instruct the model to emit ``action_hint`` markdown fences for the frontend to render as clickable settings shortcuts. Two trigger scenarios: * ``onboarding``: the user's MEMORY.md is scarce (very short, or contains no identity hint such as a name). * ``browser-tools``: the user needs a cap...
Raccoon-Office/Box-Agent
box_agent/acp/action_hints.py
.py
df2480453dbf7208
7.48
8
"""Clean entry point for the standalone ACP runtime binary. PyInstaller freezes this module as the main script. It must NOT import anything at module level that prints to stdout — the ACP protocol owns stdout exclusively. """ import json import os import sys WEB_EXTRACT_MCP_ARG = "--web-extract-mcp" BOOTSTRAP_MCP_...
Raccoon-Office/Box-Agent
box_agent/acp/runtime_entry.py
.py
bf0e8c19e0f89b32
7.48
8
"""Local stdio bridge for ACP that lifts the StreamReader buffer ceiling. The upstream ``acp.stdio.stdio_streams()`` constructs ``asyncio.StreamReader()`` without a ``limit`` argument, which defaults to 64 KiB. A single JSON-RPC frame on stdin that exceeds that (e.g. a ``session/prompt`` carrying base64-inlined images...
Raccoon-Office/Box-Agent
box_agent/acp/stdio_compat.py
.py
ae61ea8c2a37cc67
7.48
8
"""Shared request-auth helpers for hosted Box-Agent integrations.""" from __future__ import annotations import os import json from collections.abc import Mapping from pathlib import Path from typing import Any from urllib.parse import urlparse AUTH_TOKEN_ENV_VARS = ( "BOX_AGENT_AUTH_TOKEN", "OFFICEV3_AUTH_TO...
Raccoon-Office/Box-Agent
box_agent/auth.py
.py
95e71643c5901cc7
7.48
8
"""CLI permission negotiator — interactive terminal prompt.""" from __future__ import annotations import asyncio import sys from pathlib import Path from .tools.permissions import GrantStore class CLIPermissionNegotiator: """In-band permission negotiation via interactive terminal prompt. When a tool is de...
Raccoon-Office/Box-Agent
box_agent/cli_permissions.py
.py
326fb3e29682e785
7.48
8
"""Session-local model-context resource tracking. Only complete read-file messages that still exist verbatim in model history contribute coverage. Receipts are diagnostic references, never coverage sources. """ from __future__ import annotations import hashlib from dataclasses import dataclass from enum import Enum...
Raccoon-Office/Box-Agent
box_agent/context_resources.py
.py
6ec0bac3e78e5b94
7.48
8
"""Base class for LLM clients.""" from abc import ABC, abstractmethod from collections.abc import AsyncIterator from typing import Any from ..auth import request_auth_headers from ..client_info import current_client_headers from ..retry import RetryConfig from ..schema import LLMResponse, Message, StreamEvent HOSTED...
Raccoon-Office/Box-Agent
box_agent/llm/base.py
.py
5d856e89ba5e1d92
7.48
8
"""Translate raw LLM provider exceptions into friendly, user-facing messages. Providers surface failures as opaque exceptions whose ``str()`` is often a raw JSON blob, e.g.:: Error code: 400 - {'error': {'code': 'content_filter', 'message': ...}} Dumping that straight to the user is unfriendly. ``humanize_llm_er...
Raccoon-Office/Box-Agent
box_agent/llm/error_messages.py
.py
270ac94abfe56342
7.48
8
"""Lightweight LLM completion service. Single-shot prompts (titles, summaries, rewrites) that must NOT spin up an Agent session, load tools/skills/MCP, touch memory, or write to conversation history. Wraps :func:`LLMClient.generate` with a hard timeout, no tools, no extended thinking, and a structured result. The ACP...
Raccoon-Office/Box-Agent
box_agent/llm/lightweight.py
.py
e1f3d95ba5426d6d
7.48
8
"""Unwrap inline `<think>...</think>` blocks from LLM text output. Some providers (notably MiniMax M2.x and several GLM/Qwen variants) embed chain-of-thought directly in the text/content stream as `<think>...</think>` instead of using a dedicated `thinking` channel. Box-Agent treats those text deltas as user-facing co...
Raccoon-Office/Box-Agent
box_agent/llm/think_tag_splitter.py
.py
f96abfb91cb9a595
7.48
8
"""Per-turn token accounting via a context-local accumulator. Every LLM call in the system funnels through :class:`LLMClient` (``generate`` / ``generate_stream``) — the main multi-step loop, the Layer-2 summarization call, and the background ``MemoryExtractor``. By recording usage at that single choke point into a co...
Raccoon-Office/Box-Agent
box_agent/llm/token_meter.py
.py
4ab07abcd255eb61
7.48
8
"""Agent run logger""" import json from datetime import datetime from pathlib import Path from typing import Any, Mapping from .llm.debug_logging import ( full_payload_logging_enabled, summarize_request_payload_for_logging, ) from .schema import Message, ToolCall class AgentLogger: """Agent run logger ...
Raccoon-Office/Box-Agent
box_agent/logger.py
.py
8aa4bea29b38684f
7.48
8
"""Shared markers for content omitted from model-facing history.""" from __future__ import annotations from pathlib import Path from typing import Any MODEL_HISTORY_PLACEHOLDER_PREFIXES = ( "[Full tool-call argument omitted from model history]", "[Full file content omitted from model history]", "[Full t...
Raccoon-Office/Box-Agent
box_agent/model_history.py
.py
318224078e08fa3e
7.48
8
"""Elegant retry mechanism module Provides decorators and utility functions to support retry logic for async functions. Features: - Supports exponential backoff strategy - Configurable retry count and intervals - Supports specifying retryable exception types - Detailed logging - Fully decoupled, non-invasive to busin...
Raccoon-Office/Box-Agent
box_agent/retry.py
.py
ef021277ef597664
7.48
8
""" LangChain Integration Example Demonstrates how to integrate LangChain with an LLM Router. Simply change the base_url in the constants module! """ from langchain_core.messages import HumanMessage, SystemMessage from langchain_core.prompts import ChatPromptTemplate from langchain_core.output_parsers import StrOutpu...
radlab-dev-group/llm-router
examples/langchain_example.py
.py
61dcffefe94ba17b
7.56
12
""" LiteLLM Integration Example Demonstrates how to use LiteLLM as a proxy for an LLM Router. LiteLLM provides a unified API for 100+ LLM providers. """ import asyncio import litellm from litellm import completion, acompletion, Router, Cache from constants import HOST, MODELS class LiteLLMExamples: """ Hel...
radlab-dev-group/llm-router
examples/litellm_example.py
.py
0775c713f0e34d85
7.56
12
""" LlamaIndex Integration Example Demonstrates how to integrate LlamaIndex with an LLM Router. Simply change the base_url in the constants module! "openai_models": { "gpt-3.5-turbo": { "providers": [ { "id": "gpt_35_turbo-gemma3_12b-vllm-71:7000", "api_host": "http://192.168.10...
radlab-dev-group/llm-router
examples/llamaindex_example.py
.py
e6d57a3fdeff8291
7.56
12
""" Base constants for the llm‑router project. All values are read from environment variables that share the common prefix defined in :class:_DontChangeMe. This module deliberately contains no runtime logic – it only supplies immutable configuration values and enumerations that are shared across the code‑base. """ cl...
radlab-dev-group/llm-router
llm_router_api/base/constants_base.py
.py
ca9c04024f4f44f0
7.56
12
""" Anthropic API integration utilities. """ from __future__ import annotations import datetime from typing import Any, Dict from llm_router_api.core.api_types.types_i import ApiTypesI class AnthropicType(ApiTypesI): """ Concrete descriptor for Anthropic endpoints. """ def chat_ep(self) -> str: ...
radlab-dev-group/llm-router
llm_router_api/core/api_types/anthropic.py
.py
d913e2b1e466dd9f
7.56
12
""" Ollama API integration utilities. This module supplies two primary building blocks for the *llm‑router* project: 1. **OllamaType** – a concrete implementation of :class:`llm_router_api.core.api_types.types_i.ApiTypesI`. It maps the internal routing logic to the Ollama HTTP endpoints, exposing the relative ...
radlab-dev-group/llm-router
llm_router_api/core/api_types/ollama.py
.py
ee315e24988f4796
7.56
12
from __future__ import annotations from typing import Any, Dict from abc import ABC, abstractmethod class ApiTypesI(ABC): """ """ @staticmethod def tags(models_config: Dict[str, Any]) -> Dict[str, Any]: """ Convert the provided config dict with keys like "google_models", "openai_...
radlab-dev-group/llm-router
llm_router_api/core/api_types/types_i.py
.py
9fe787d4c1819f5c
7.56
12
""" Module providing the vLLM API type implementation. The :class:VllmType class describes the endpoint paths and HTTP methods required to interact with a vLLM server that exposes an OpenAI‑compatible REST interface. """ from __future__ import annotations from typing import Any, Dict from llm_router_api.core.api_typ...
radlab-dev-group/llm-router
llm_router_api/core/api_types/vllm.py
.py
32191d4ccc73f1b9
7.56
12
""" Module providing a simple auditing mechanism for request logs. The :class:`AnyRequestAuditor` class accepts a standard :class:`logging.Logger` instance and forwards audit entries to a storage backend defined by ``DEFAULT_AUDITOR_STORAGE_CLASS``. The default implementation stores logs using GPG encryption via :cla...
radlab-dev-group/llm-router
llm_router_api/core/auditor/auditor.py
.py
c4c14601ba5cde56
7.56
12
""" Implementation of an audit‑log storage backend that encrypts logs using GPG. The :class:`GPGAuditorLogStorage` class conforms to the :class:`~llm_router_api.core.auditor.log_storage.log_storage_interface.AuditorLogStorageInterface` protocol. It writes each log entry to a timestamped file inside ``logs/auditor`` a...
radlab-dev-group/llm-router
llm_router_api/core/auditor/log_storage/gpg.py
.py
2de29e99e865c8e0
7.56
12
""" Abstract definition for audit‑log storage back‑ends. Any concrete implementation must inherit from :class:`AuditorLogStorageInterface` and provide a :meth:`store_log` method that persists the supplied audit record. This contract allows different storage strategies (e.g., encrypted files, databases, cloud buckets)...
radlab-dev-group/llm-router
llm_router_api/core/auditor/log_storage/log_storage_interface.py
.py
5b3bb40edc67fd6d
7.56
12
""" Authentication auditor — bridges auth events to the existing AnyRequestAuditor for compliance/logging. """ from __future__ import annotations from typing import Dict, Optional from llm_router_api.core.auditor.auditor import AnyRequestAuditor class AuthAuditorBridge: """ Bridge between auth middleware a...
radlab-dev-group/llm-router
llm_router_api/core/auth/audit.py
.py
4ff1db261b1e228d
7.56
12
""" Auth error codes and messages. """ from __future__ import annotations from dataclasses import dataclass from typing import Any, Dict, Optional @dataclass(frozen=True) class AuthResult: """ Result of the authentication & authorization check. Attributes ---------- allowed : bool Wheth...
radlab-dev-group/llm-router
llm_router_api/core/auth/errors.py
.py
4012b4ecebe79f55
7.56
12
""" API key generator. Generates keys in the format ``sk-litm-<base62>`` matching the standard used by OpenAI, LiteLLM, and other LLM proxies. """ from __future__ import annotations import re import string import secrets from typing import Tuple class KeyGenerator: """ Generate API keys and validate their...
radlab-dev-group/llm-router
llm_router_api/core/auth/key_generator.py
.py
9ed2930f47c6a7e2
7.56
12
""" Key store factory — selects the concrete backend based on ``store_type``. """ from __future__ import annotations import os import secrets from typing import Optional, Tuple from llm_router_api.core.auth.key_store.memory import MemoryKeyStore from llm_router_api.core.auth.key_store.interface import KeyStoreInter...
radlab-dev-group/llm-router
llm_router_api/core/auth/key_store/__init__.py
.py
54ca179f4c05a518
7.56
12
""" Shared helpers for API key record construction across all KeyStore backends. All KeyStore implementations (Memory, Redis, Vault) use the same key-prefix algorithm and default field values — this module centralizes them. """ from __future__ import annotations import uuid from typing import Dict def gen_key_pre...
radlab-dev-group/llm-router
llm_router_api/core/auth/key_store/_record_helpers.py
.py
60df250b87c81147
7.56
12
""" Redis key store — stores API keys directly in Redis. Uses a Redis **string** (JSON-serialized) per key under ``secret:llm-router:api-keys:<key_id>``. Suitable for deployments without HashiCorp Vault. """ from __future__ import annotations import json import time import uuid import redis import bcrypt from typin...
radlab-dev-group/llm-router
llm_router_api/core/auth/key_store/redis_store.py
.py
7984599bfb29b64a
7.56
12
""" Prometheus metrics for the auth layer. These metrics are registered alongside the existing HTTP metrics when Prometheus is enabled (``LLM_ROUTER_USE_PROMETHEUS=true``). """ from __future__ import annotations import os from llm_router_api.core.metrics_handler import MetricsHandler IS_PROMETHEUS_AVAILABLE = Fal...
radlab-dev-group/llm-router
llm_router_api/core/auth/metrics.py
.py
3396e10d9c1cba75
7.56
12
""" Data models for the auth layer. """ from __future__ import annotations from dataclasses import dataclass, field from typing import Dict, Optional, Tuple @dataclass(frozen=True) class EndpointPermission: """ What a given API key may do on a specific endpoint. Attributes ---------- method : s...
radlab-dev-group/llm-router
llm_router_api/core/auth/policies/model.py
.py
0cacba9e69a2cc53
7.56
12
""" Redis-backed sliding window rate limiter. Uses sorted sets to track request timestamps per key+IP, enforcing per-minute rate limits without fixed-window boundary artifacts. """ from __future__ import annotations import time import uuid import redis from typing import Optional from dataclasses import dataclass ...
radlab-dev-group/llm-router
llm_router_api/core/auth/rate_limiter.py
.py
284321809ffb8f93
7.56
12
""" llm_router_api.core.decorators ============================== Utility decorators used by the REST‑endpoint classes. The project’s endpoint hierarchy (`EndpointI` and `EndpointWithHttpRequestI`) relies on two cross‑cutting concerns: * **Parameter validation** – every endpoint can declare a list of required argu...
radlab-dev-group/llm-router
llm_router_api/core/decorators.py
.py
4a26f07f0d275714
7.56
12
""" Utility helpers for representing API errors as JSON‑serializable dictionaries. This module centralizes the creation of error payloads that can be returned from Flask (or any other) endpoints. By keeping the structure in one place, we avoid repetition and make it easy to evolve the error format in the future. """ ...
radlab-dev-group/llm-router
llm_router_api/core/errors.py
.py
e069272487601478
7.56
12
#!/usr/bin/env python3 """Build a stratified evaluation set for position labels — any regulation. Proportional sampling is useless on a docket with a lopsided split. This one is ~96% Oppose, so 200 random comments give ~192 Oppose and the metric that actually broke (Support precision) would rest on six rows. Allocatio...
abigailhaddad/generic-comment-analyzer
build_eval_set.py
.py
49be28dae906f4a0
7.48
8
#!/usr/bin/env python3 """Draft CANDIDATE labels for an evaluation set, with enough reasoning to review by hand. These are model output, not ground truth. The point is to make human review cheap and *checkable*: for every comment the model must quote the words it relied on, argue its own call, argue the strongest case...
abigailhaddad/generic-comment-analyzer
label_eval_set.py
.py
57b3c33a84cf8be8
7.48
8
#!/usr/bin/env python3 """Pull every figure used in the OMB write-up straight from the parquet. Reuses generate_report.py's own aggregation functions, so the numbers here are guaranteed identical to the dashboard. Re-run after the pipeline updates to get fresh figures for the doc. python report_numbers.py --regul...
abigailhaddad/generic-comment-analyzer
report_numbers.py
.py
82373ca364aff809
7.48
8
#!/usr/bin/env python3 """Score the classifier's positions against the reviewed evaluation set. Reports per-class precision and recall, plus a confusion matrix, and writes the data behind the public accuracy page. Per-class is the point: the defect that prompted all this was Support precision, which a single overall a...
abigailhaddad/generic-comment-analyzer
score_stances.py
.py
3017a3a08b8f6572
7.48
8
"""Shared fixtures for frontend E2E tests.""" import os import subprocess import time import pytest from playwright.sync_api import sync_playwright PORT = 8111 BASE_URL = f"http://localhost:{PORT}" REPORT_FILE = "index.html" ROOT_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # Se...
abigailhaddad/generic-comment-analyzer
tests/frontend/conftest.py
.py
f26ad1287d8e0f60
7.98
8
"""Test DataTables sorting, pagination, and search.""" import pytest def test_table_has_correct_columns(page): """Table headers match expected columns.""" headers = page.query_selector_all("#commentsTable thead th") header_texts = [h.inner_text().strip() for h in headers if h.is_visible()] assert "ID...
abigailhaddad/generic-comment-analyzer
tests/frontend/test_datatables.py
.py
5829ffec3be9d69d
7.98
8
"""Test that the report page loads correctly.""" import pytest def test_page_title(page): """Page title contains regulation name.""" assert "Comment Analysis Report" in page.title() or "Analysis" in page.title() def test_stat_cards_visible(page): """Summary stat cards are rendered.""" cards = page....
abigailhaddad/generic-comment-analyzer
tests/frontend/test_page_loads.py
.py
d5a2ef12f2479637
7.98
8
"""Tests for the 'Read the Rule' page (read-the-rule.html). Only runs when the served regulation has a rule page (built from rule_sections.json). Skipped otherwise (a regulation without rule_sections.json). The served regulation is chosen the same way as in conftest (TEST_REGULATION, default omb-financial-assistance)....
abigailhaddad/generic-comment-analyzer
tests/frontend/test_rule_page.py
.py
c4680a07a77917e2
7.98
8
"""Test shareable URL filter sync.""" import pytest def _open_column_filter(page, label): page.click("#addFilterBtn") page.wait_for_selector(".filter-modal .filter-option") page.locator(".filter-modal .filter-option", has_text=label).first.click() page.wait_for_selector(".filter-modal .filter-options...
abigailhaddad/generic-comment-analyzer
tests/frontend/test_url_sync.py
.py
f71d5603d8627f3d
7.98
8
"""Tests for the Read-the-Rule page's presence guard. read-the-rule.html is built only when rule_sections.json is present, and the report links to it only in the same case. Both halves failing together is what made this dangerous: rule_sections.json is gitignored and was never synced from R2, so CI checkouts never had...
abigailhaddad/generic-comment-analyzer
tests/test_rule_page_guard.py
.py
a1fe54395be6be8b
7.98
8
"""Tests for the anti-shrink guard in save_results. The guard exists so a stray `--sample` or `--reprocess` cannot quietly replace a 157k-row canonical parquet with 5 rows. It was dead code from the day it was written: it counted rows with `pd.read_parquet(path, columns=[])`, which returns a frame with no columns AND ...
abigailhaddad/generic-comment-analyzer
tests/test_save_guard.py
.py
1a1a77a7bd09c410
7.98
8
from __future__ import print_function __all__ = ["BrowseFilter", "Result", "Results"] from typing import Any, Iterable, List, Mapping, Sequence, Union from java.lang import Object from com.inductiveautomation.ignition.common import Path, QualifiedPath from com.inductiveautomation.ignition.common.config import Prope...
ignition-devs/ignition-api
src/com/inductiveautomation/ignition/common/browsing/__init__.py
.py
ab6c5941a4cb94c8
7.5
9
from __future__ import annotations from dataclasses import dataclass, field from typing import Any @dataclass(frozen=True) class RuntimeArgument: """Command argument exposed through the runtime-facing contract.""" model_id: str symbol_name: str value_type: str minimum: float | int | None = None ...
FAROTECH/orbitfabric
src/orbitfabric/gen/runtime/contract.py
.py
5e0071480af08cbc
7.42
6
from __future__ import annotations import re _IDENTIFIER_PARTS = re.compile(r"[A-Za-z0-9]+") def to_pascal_case(model_id: str) -> str: """Convert a Mission Model identifier to a deterministic PascalCase symbol.""" parts = _identifier_parts(model_id) if not parts: return "Unnamed" return ""....
FAROTECH/orbitfabric
src/orbitfabric/gen/runtime/naming.py
.py
f45039e74d9c8d5a
7.42
6
"""Manual conversation compaction interoperable with deepagents' SummarizationMiddleware. The pure state-arithmetic helpers delegate to a live ``SummarizationMiddleware`` instance so the logic exists in exactly one place (upstream). This module keeps only what deepagents does not provide or deliberately does different...
arrase/ollama-agent
ollama_agent/agent/compaction.py
.py
8df9a7f6bfb84db6
7.66
20
"""Shared type definitions and utilities for the application.""" from __future__ import annotations import re from typing import Any, Literal, TypedDict from ..i18n import _ # Reasoning effort types ReasoningEffortValue = Literal["low", "medium", "high", "xhigh", "disabled", "hide", "enabled"] ALLOWED_REASONING_EFF...
arrase/ollama-agent
ollama_agent/core/common.py
.py
254918cd24d99f54
7.66
20
"""Model capabilities, runtime creation, and validation logic.""" from __future__ import annotations import re from typing import Any, Callable, cast import ollama from langchain_ollama import ChatOllama from pydantic import Field from ..i18n import _ from .common import ( ALLOWED_REASONING_EFFORTS, DEFAULT...
arrase/ollama-agent
ollama_agent/core/models.py
.py
fff20b57447b81d7
7.66
20
"""Internationalization (i18n) support for ollama-agent.""" from __future__ import annotations import json import locale import os from importlib import resources from typing import Any SUPPORTED_LOCALES: tuple[str, ...] = ( "en", "es", "fr", "de", "it", "pt", "zh", "ja", "ru", ...
arrase/ollama-agent
ollama_agent/i18n/__init__.py
.py
9fca439d89f9b274
7.66
20
"""System clipboard integration utilities for macOS, Linux, and Windows.""" from __future__ import annotations import ctypes import os import shutil import subprocess import sys class ClipboardError(Exception): """Raised when a system clipboard operation fails.""" def _copy_via_command(cmd: list[str], text: s...
arrase/ollama-agent
ollama_agent/interfaces/clipboard.py
.py
2e3bd5062a85ef40
7.66
20
"""MCP server initialization and loading routines.""" from __future__ import annotations import asyncio import json import logging import os import re from typing import Any from langchain_mcp_adapters.client import MultiServerMCPClient from ..i18n import _ from ..settings import MCP_PATH, SubAgentMCPServer _log = ...
arrase/ollama-agent
ollama_agent/mcp/loader.py
.py
c7074c60e248013e
7.66
20
"""Shared RAG management commands used by CLI and REPL.""" from __future__ import annotations from dataclasses import dataclass, field from rich.console import Console from rich.table import Table from ..i18n import _ from .manager import RAGError, RAGManager class RAGDatabaseNotFoundError(RAGError): """Raise...
arrase/ollama-agent
ollama_agent/rag/commands.py
.py
10a4c3c33c085fd1
7.66
20
"""RAG manager for document storage and retrieval using Qdrant.""" from __future__ import annotations import logging import shutil import uuid from pathlib import Path from typing import Any import ollama from qdrant_client import QdrantClient from qdrant_client.models import ( Distance, FieldCondition, ...
arrase/ollama-agent
ollama_agent/rag/manager.py
.py
814deab5df7d92b5
7.66
20
"""Shared skill management commands used by CLI and REPL.""" from __future__ import annotations from dataclasses import dataclass, field from rich.console import Console from rich.markdown import Markdown from rich.panel import Panel from rich.table import Table from ..core.resource_manager import require_text, res...
arrase/ollama-agent
ollama_agent/skills/commands.py
.py
77ac4718aa3b246a
7.66
20
"""Skill management utilities following the Agent Skills specification.""" from __future__ import annotations import re import shutil from dataclasses import dataclass from pathlib import Path from typing import Any import yaml # type: ignore[import-untyped] from ..core import BaseFileStoreManager, validate_identi...
arrase/ollama-agent
ollama_agent/skills/manager.py
.py
8490b082ed7975d9
7.66
20
"""Base classes for streaming renderers.""" from __future__ import annotations import logging from abc import ABC, abstractmethod from typing import TYPE_CHECKING, Any if TYPE_CHECKING: from ..agent import AgentRuntime _log = logging.getLogger(__name__) class StreamingRenderer(ABC): """Abstract base class...
arrase/ollama-agent
ollama_agent/streaming/base.py
.py
cc12434bf948ef30
7.66
20
"""Streaming chunk parsers for LangChain / DeepAgents events. These functions extract structured text from the raw streaming payloads produced by LangChain chat models and DeepAgents, keeping :mod:`~ollama_agent.agent.agent` focused solely on agent initialisation and workflow orchestration. """ from __future__ import...
arrase/ollama-agent
ollama_agent/streaming/parsers.py
.py
80a75df8a7e6e175
7.66
20
"""Shared task management commands used by CLI and REPL.""" from __future__ import annotations from dataclasses import dataclass, field from rich.console import Console from rich.table import Table from ..agent import AgentRuntime from ..core import DEFAULT_REASONING_EFFORT from ..core.resource_manager import requi...
arrase/ollama-agent
ollama_agent/tasks/commands.py
.py
821d93db186a2d40
7.66
20
"""Task management utilities.""" from __future__ import annotations import os from dataclasses import asdict, dataclass, field from pathlib import Path from typing import Any import yaml # type: ignore[import-untyped] from ..core import ( BaseFileStoreManager, DEFAULT_REASONING_EFFORT, ReasoningEffortV...
arrase/ollama-agent
ollama_agent/tasks/manager.py
.py
18675e9eb9e36cff
7.66
20
#!/usr/bin/env python3 """ Simplified setup.py for madengine This setup.py provides compatibility with environments that require traditional setup.py installations while reading configuration from pyproject.toml. For modern installations, prefer: pip install . python -m build pip install -e .[dev] For l...
ROCm/madengine
setup.py
.py
0a6a84b3e6edf29d
7.5
9
#!/usr/bin/env python3 """ Main CLI Application for madengine This module contains the main Typer app and entry point for the madengine CLI. Copyright (c) Advanced Micro Devices, Inc. All rights reserved. """ import sys from importlib.metadata import PackageNotFoundError, version as pkg_version import typer from ri...
ROCm/madengine
src/madengine/cli/app.py
.py
af0b015eb0450323
7.5
9
#!/usr/bin/env python3 """ Report command for madengine CLI This module provides report generation commands including CSV to HTML and CSV to email conversions. Copyright (c) Advanced Micro Devices, Inc. All rights reserved. """ import os from pathlib import Path import typer from rich.panel import Panel try: f...
ROCm/madengine
src/madengine/cli/commands/report.py
.py
7ae217d487e29093
7.5
9