Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /ctrl-gaurav_effGen /website /scripts /gen_site_data.py
#!/usr/bin/env python3
"""Derive every count and list the website states, straight from the installed
effGen package, and write them to ``data/effgen.json``.
The site used to type its numbers into JSX, which is how it came to advertise a
tool count, a model count and a version that the framework had moved past. This
script is the replacement: one file on disk, generated by one command, imported
by both codebases.
python scripts/gen_site_data.py # write data/effgen.json
python scripts/gen_site_data.py --check # exit 1 if it is stale
python scripts/gen_site_data.py --stdout # print, write nothing
Everything here is introspected from the live package or parsed out of the real
``--help`` output, so it cannot drift from what is installed. The one figure that
is a snapshot rather than a computation is the model catalog, which ships with
the package; ``effgen models refresh`` updates it.
Run it with the framework's environment on PATH::
export PATH=/path/to/your/effgen/env/bin:$PATH # or activate it however you do
unset EFFGEN_BASE_URL OPENAI_BASE_URL OPENAI_API_BASE
python scripts/gen_site_data.py
``--check`` is what CI and the verification wave run: it regenerates in memory
and compares against the checked-in file, ignoring ``derived_at``, so a stale
count fails the build instead of reaching a page.
"""
from __future__ import annotations
import argparse
import json
import re
import subprocess
import sys
from datetime import datetime, timezone
from pathlib import Path
REPO = Path(__file__).resolve().parent.parent
OUT = REPO / "data" / "effgen.json"
# Local inference engines. These are not provider adapters — they run weights on
# the machine effGen is running on — so they are listed separately everywhere the
# site talks about "where a model can come from".
LOCAL_ENGINES = ["transformers", "vllm", "gguf", "mlx"]
def _cli(*args: str) -> str:
"""Run the real `effgen` binary and return its stdout."""
proc = subprocess.run(
["effgen", *args],
capture_output=True,
text=True,
timeout=120,
)
if proc.returncode != 0 and not proc.stdout:
raise RuntimeError(f"effgen {' '.join(args)} failed: {proc.stderr[:400]}")
return proc.stdout
def collect_version() -> dict:
from importlib.metadata import metadata, version
meta = metadata("effgen")
classifiers = meta.get_all("Classifier") or []
pythons = sorted(
c.rsplit(":", 1)[1].strip()
for c in classifiers
if c.startswith("Programming Language :: Python :: 3.")
)
return {
"version": version("effgen"),
"python_versions": pythons,
"python_requires": meta.get("Requires-Python", ""),
}
def collect_public_surface() -> dict:
import effgen
return {"public_names": len(effgen.__all__)}
def _example_arguments(md) -> tuple[dict, str]:
"""The arguments to show in a tool's snippet, taken from the tool itself.
A tool's metadata carries its own worked examples, and where it does, the
first one is the call the gallery shows — the values come from whoever wrote
the tool, not from whoever wrote the page. Those examples also carry the
output they produced, under an ``output`` key; that is illustrative and is
dropped here, because the site shows output it ran for itself or none at
all.
A tool with no example falls back to its required parameters, filled from
the schema: the first allowed value of an enum, or a placeholder named after
the type. The second return value says which of the two happened, so the
page can mark a snippet whose arguments are placeholders rather than
presenting it as a call that would run.
"""
placeholders = {
"string": "...",
"integer": 1,
"number": 1,
"boolean": True,
"array": [],
"object": {},
}
example = (md.examples or [None])[0]
if isinstance(example, dict):
args = {k: v for k, v in example.items() if k != "output"}
if args:
return args, "tool"
args = {}
for spec in md.parameters or []:
if not spec.required:
continue
if spec.enum:
args[spec.name] = spec.enum[0]
else:
kind = getattr(spec.type, "value", str(spec.type))
args[spec.name] = placeholders.get(kind, "...")
return args, "schema"
def collect_tools() -> dict:
"""Every built-in tool, with the category it is filed under.
The gallery on the site renders straight from this, so the description, the
parameter table and the arguments in the snippet are all the tool's own
metadata rather than a paraphrase of it.
"""
from effgen.tools import get_registry
registry = get_registry()
registry.discover_builtin_tools()
metadata = registry.get_all_metadata()
tools = []
for name in sorted(metadata):
md = metadata[name]
cls = type(registry.get_tool_sync(name))
tools.append(
{
"name": name,
"class_name": cls.__name__,
"module": cls.__module__,
"category": getattr(md.category, "value", str(md.category)),
"description": md.description,
"tags": list(md.tags or []),
"requires_api_key": bool(md.requires_api_key),
"requires_auth": bool(md.requires_auth),
"requires_approval": bool(md.requires_approval),
"cost_estimate": md.cost_estimate,
"timeout_seconds": md.timeout_seconds,
"parameters": len(md.parameters or []),
"params": [
{
"name": spec.name,
"type": getattr(spec.type, "value", str(spec.type)),
"required": bool(spec.required),
"default": spec.default,
"enum": list(spec.enum) if spec.enum else None,
"description": spec.description,
}
for spec in md.parameters or []
],
"example_arguments": _example_arguments(md)[0],
"example_source": _example_arguments(md)[1],
}
)
categories: dict[str, list[str]] = {}
for tool in tools:
categories.setdefault(tool["category"], []).append(tool["name"])
return {
"count": len(tools),
"categories": {k: categories[k] for k in sorted(categories)},
"category_counts": {k: len(categories[k]) for k in sorted(categories)},
"items": tools,
}
def collect_presets() -> dict:
"""Every preset, with the tool-schema cost of using it.
``approx_tokens_per_call`` is what ``effgen presets`` prints as
``~N tok/call``: the size of the tool schemas sent on every request. It is
the figure that decides whether a preset fits a small-context or
rate-limited model, so the gallery shows it beside the tool count.
"""
from effgen.presets import get_preset, list_presets
from effgen.presets.registry import preset_tool_overhead
names = list(list_presets())
items = []
for name in names:
preset = get_preset(name)
_, approx_tokens = preset_tool_overhead(name)
items.append(
{
"name": preset.name,
"description": preset.description,
"tools": list(preset.tool_names or []),
"tool_count": len(preset.tool_names or []),
"approx_tokens_per_call": approx_tokens,
"temperature": preset.temperature,
"max_iterations": preset.max_iterations,
"enable_memory": bool(preset.enable_memory),
"enable_sub_agents": bool(preset.enable_sub_agents),
"tags": list(preset.tags or []),
}
)
return {"count": len(items), "items": items}
def collect_prompts() -> dict:
"""Two distinct surfaces, and the site has to say which it means.
``templates`` counts every registered template. ``library`` counts the
curated domain prompts that ``effgen prompts list`` shows — a smaller number,
and the one a reader will see if they run the command.
"""
from effgen.prompts import create_default_template_manager
from effgen.prompts.library import registry as library
templates = create_default_template_manager().list_templates()
prompts = library.all()
by_domain: dict[str, list[str]] = {}
for prompt in prompts:
by_domain.setdefault(prompt.domain, []).append(prompt.name)
return {
"templates": len(templates),
"library": len(prompts),
"domains": sorted(library.domains()),
"domain_counts": {k: len(by_domain[k]) for k in sorted(by_domain)},
"items": [
{
"name": p.name,
"domain": p.domain,
"variant": p.variant,
"description": p.description,
"tags": list(p.tags or []),
"variables": _template_variables(p),
"fixture_keys": sorted((p.fixture or {}).keys()),
"check": _expected_shape(p),
}
for p in sorted(prompts, key=lambda p: (p.domain, p.name))
],
"template_names": sorted(templates),
}
def _template_variables(prompt) -> list[dict]:
"""The inputs a library template renders with, out of its own JSON schema.
The schema is what ``render()`` validates against, so the gallery's variable
table cannot drift from what the template will actually accept.
"""
schema = prompt.input_schema or {}
required = set(schema.get("required") or ())
out = []
for name, spec in (schema.get("properties") or {}).items():
out.append(
{
"name": name,
"type": spec.get("type", "string"),
"required": name in required,
"description": spec.get("description", ""),
"enum": list(spec["enum"]) if spec.get("enum") else None,
}
)
return out
def _expected_shape(prompt) -> str:
"""How a template's output is checked: as JSON, against a regex, or by a function."""
shape = prompt.expected_shape or {}
kind = shape.get("type")
if kind == "callable":
return "function"
return str(kind) if kind else "none"
def collect_models() -> dict:
"""Provider adapters, and the catalog each one ships.
Ten adapters are registered. Nine of them carry a bundled catalog;
``openai_compatible`` carries none, because it serves whatever the endpoint
it is pointed at serves. Both numbers are true and the site has to say which
one it means, so both are recorded here.
"""
from effgen.models import _catalog, registry as model_registry
providers = sorted(model_registry.list_providers())
per_provider = {p: len(model_registry.list_models(p)) for p in providers}
with_catalog = [p for p in providers if per_provider[p] > 0]
# One row per adapter for the provider table: how many models it carries,
# which one it reaches for when a call names no model, when the catalog was
# last checked against the provider's live API, and what the catalog says
# those models can do. `has_credentials()` is deliberately not read — it
# answers whether *this machine* holds a key, which is not a fact about
# effGen and must never reach a page.
from effgen.models.registry import ProviderRegistry
rows = []
for name in providers:
try:
records = _catalog.list_models(name)
meta = _catalog.snapshot_meta(name) or {}
default = _catalog.default_model(name)
except Exception: # noqa: BLE001 - an adapter with no bundled catalog
records, meta, default = [], {}, None
contexts = [r.context_window for r in records if r.context_window]
# Which environment variable the adapter reads. That is a fact about
# effGen, unlike `has_credentials()`, which answers whether *this*
# machine holds a key and must never reach a page.
env_keys = ProviderRegistry.get_provider_info(name).get("env_keys", [])
rows.append(
{
"name": name,
"env_keys": list(env_keys),
"models": len(records),
"default": default,
"verified_on": meta.get("verified_on"),
"source": meta.get("source"),
"supports_tools": sum(1 for r in records if r.supports_tools),
"supports_vision": sum(1 for r in records if r.supports_vision),
"supports_audio": sum(1 for r in records if r.supports_audio),
"free_tier": sum(1 for r in records if r.free_tier),
"priced": sum(1 for r in records if r.is_priced),
"max_context": max(contexts) if contexts else None,
}
)
totals = {
key: sum(row[key] for row in rows)
for key in ("supports_tools", "supports_vision", "supports_audio", "free_tier", "priced")
}
return {
"adapters": providers,
"adapter_count": len(providers),
"with_catalog": with_catalog,
"with_catalog_count": len(with_catalog),
"models": sum(per_provider.values()),
"models_by_provider": per_provider,
"providers": rows,
"capability_totals": totals,
"local_engines": LOCAL_ENGINES,
}
# argparse writes a sub-command group into the usage line as a braced list
# followed by an ellipsis: `usage: effgen tools [-h] {list,info,test} ...`. A
# choice-constrained option looks similar (`--kind {run,eval}`) but never carries
# the ellipsis, which is what separates the two.
SUBCOMMAND_GROUP = re.compile(r"\{([a-z0-9_,\-]+)\}\s*(?:\n\s*)?\.\.\.")
def _subcommands(command: str) -> list[str]:
"""The sub-commands one top-level command declares, from its own --help."""
match = SUBCOMMAND_GROUP.search(_cli(command, "--help"))
if not match:
return []
return [c for c in match.group(1).split(",") if c]
def collect_cli() -> dict:
"""The command surface, parsed out of the real ``--help`` output.
argparse prints the command list as a single braced group; the per-command
blurb follows it, indented. Both are read here rather than maintained by
hand, because the site states the command count in several places.
"""
root = _cli("--help")
group = SUBCOMMAND_GROUP.search(root)
if not group:
raise RuntimeError("could not find the command group in `effgen --help`")
commands = [c for c in group.group(1).split(",") if c]
# The blurb for each command, from the "positional arguments" block. argparse
# wraps long ones onto continuation lines indented further than the name.
blurbs: dict[str, str] = {}
current = None
for line in root.splitlines():
head = re.match(r"^ ([a-z][a-z0-9\-]*)\s{2,}(.*)$", line)
if head and head.group(1) in commands:
current = head.group(1)
blurbs[current] = head.group(2).strip()
elif current and re.match(r"^\s{20,}\S", line):
blurbs[current] += " " + line.strip()
elif line.strip() == "" or line.startswith("options:"):
current = None
themes = re.search(r"--theme \{([a-z\-,]+)\}", root)
shells = re.search(r"--completion \{([a-z,]+)\}", root)
sub = {c: _subcommands(c) for c in commands}
sub = {c: v for c, v in sub.items() if v}
return {
"commands": [{"name": c, "summary": blurbs.get(c, "")} for c in commands],
"command_count": len(commands),
"subcommands": sub,
"subcommand_count": sum(len(v) for v in sub.values()),
"global_options": _options(root),
# The flag tables the product pages render. A page that lists a
# command's flags shows the command's own help text, so the table and
# the binary cannot say different things.
"command_options": {
"serve": _options(_cli("serve", "--help")),
"models browse": _options(_cli("models", "browse", "--help")),
"models info": _options(_cli("models", "info", "--help")),
"models list": _options(_cli("models", "list", "--help")),
"eval": _options(_cli("eval", "--help")),
"compare": _options(_cli("compare", "--help")),
"battle": _options(_cli("battle", "--help")),
"cost": _options(_cli("cost", "--help")),
"loadtest": _options(_cli("loadtest", "--help")),
},
# `serve` documents its operational settings as environment variables in
# an epilog block; they belong in the same table as its flags.
"serve_env": _env_settings(
_cli("serve", "--help"), "Operational settings (environment variables):"),
"themes": themes.group(1).split(",") if themes else [],
"completion_shells": shells.group(1).split(",") if shells else [],
}
# An argparse "options:" block. Each entry starts at column 2 with the flag
# spelling; its help text either follows on the same line or is indented under
# it, and wraps at column 24.
_OPTION_HEAD = re.compile(r"^ (-[^\s].*?)(?: +(.*))?$")
def _options(help_text: str) -> list[dict]:
"""Every option a command declares, read out of its own ``--help``.
The site shows these as a table, and a table that paraphrases is worse than
no table because a reader will copy from it. So the rows are the help text,
not a description of it.
"""
lines = help_text.splitlines()
try:
start = next(i for i, line in enumerate(lines) if line.rstrip() == "options:")
except StopIteration:
return []
options: list[dict] = []
current: dict | None = None
for line in lines[start + 1:]:
if line.strip() == "":
continue
# A new top-level block (Examples:, Environment:, …) ends the options.
if line[:1] not in (" ", "\t"):
break
head = _OPTION_HEAD.match(line)
if head and not line.startswith(" "):
if current:
options.append(current)
current = {"name": head.group(1).strip(), "description": (head.group(2) or "").strip()}
continue
if current is not None and line.startswith(" "):
text = line.strip()
current["description"] = f"{current['description']} {text}".strip()
if current:
options.append(current)
return [o for o in options if o["name"] != "-h, --help"]
# `effgen serve --help` names its operational settings in an epilog block rather
# than as flags, because they are environment variables. They are as much part of
# the command's surface as its four options, so the site shows them in the same
# table shape — and reads them from the same place.
_ENV_HEAD = re.compile(r"^ ([A-Z][A-Z0-9_]*(?:=\S+)?)\s*(.*)$")
def _env_settings(help_text: str, heading: str) -> list[dict]:
"""The environment variables a command documents under ``heading``."""
lines = help_text.splitlines()
try:
start = next(i for i, line in enumerate(lines) if line.startswith(heading))
except StopIteration:
return []
settings: list[dict] = []
current: dict | None = None
for line in lines[start + 1:]:
if line.strip() == "":
continue
if line[:1] not in (" ", "\t"):
break
head = _ENV_HEAD.match(line)
if head and not line.startswith(" "):
name = head.group(1).strip()
text = (head.group(2) or "").strip()
# `NAME_A / help text` continues onto a bare `NAME_B` below it.
if text.startswith("/"):
name, text = f"{name} /", text[1:].strip()
# Two variables that share one line of help are written as
# `NAME_A /` with `NAME_B` under it; the pair is one entry.
if current and current["name"].endswith("/") and not text:
current["name"] = f"{current['name'].rstrip('/ ')} / {name}"
continue
if current:
settings.append(current)
current = {"name": name, "description": text}
continue
if current is not None:
current["description"] = f"{current['description']} {line.strip()}".strip()
if current:
settings.append(current)
return settings
def collect_code() -> dict:
"""What `effgen code` and `effgen chat` offer in a session, from the package.
The slash-command tables, the git allow-list and the size of the undo
journal are read off the modules that implement them, so the two pages that
state those counts cannot drift from the shipped behaviour.
"""
from effgen.cli.chat_commands import _SLASH_COMMANDS as chat_commands
from effgen.cli.code.edits import _MAX_HISTORY
from effgen.cli.code.git_actions import (
ALLOWED_SUBCOMMANDS,
FORBIDDEN_FLAGS,
FORBIDDEN_SUBCOMMANDS,
)
from effgen.cli.code.repl_commands import _SLASH_COMMANDS as code_commands
return {
"options": _options(_cli("code", "--help")),
"slash_commands": [
{"name": name, "summary": summary} for name, summary in code_commands.items()
],
"slash_command_count": len(code_commands),
"chat_slash_commands": [
{"name": name, "summary": summary} for name, summary in chat_commands.items()
],
"chat_slash_command_count": len(chat_commands),
"undo_journal_entries": _MAX_HISTORY,
"git_allowed": sorted(ALLOWED_SUBCOMMANDS),
"git_refused": sorted(FORBIDDEN_SUBCOMMANDS),
"git_refused_flags": sorted(FORBIDDEN_FLAGS),
}
# The two web surfaces ship as static files inside the package. Everything the
# `/dashboard` page states about them — which panels exist, what the playground
# offers, how large the whole thing is, and how many external hosts it reaches —
# is read off those files rather than described from memory.
# Most panels are a `<section class="panel">`; the SLO and latency pair sit in a
# two-column row as `<div class="panel">`. Both carry the id the jump row links
# to and an `<h2>` naming them, which is what this reads.
_PANEL = re.compile(
r'<(?:section|div) class="panel[^"]*" id="(panel-[a-z\-]+)"[^>]*>\s*<h2>([^<]+)</h2>')
_NAV = re.compile(r'<a href="#([a-z\-]+)" data-panel-jump="[a-z\-]+">([^<]+)</a>')
# The framework's own test for this (tests/dx/test_dashboard.py
# ::test_no_external_assets) flags absolute and protocol-relative URLs; a
# same-origin path such as "/dashboard/data.json" is fine. Same expression here,
# so the site reports the number that test enforces.
_OFF_HOST = re.compile(r"""https?://[^\s"'()]+|(?<![:\w])//[^\s"'()]+""")
def collect_web() -> dict:
"""The dashboard and the playground, read off the files the package ships."""
import effgen
root = Path(effgen.__file__).resolve().parent
dashboard_html = (root / "dashboard" / "static" / "index.html").read_text()
playground_html = (root / "playground" / "static" / "index.html").read_text()
nav = dict(_NAV.findall(dashboard_html))
panels = [
{"id": pid, "title": title.strip(), "nav": nav.get(pid, "")}
for pid, title in _PANEL.findall(dashboard_html)
]
# The summary row and the two-column row are markup, not `panel` sections,
# so they carry their own ids and are added in the order they appear.
summary_cards = re.findall(r'<div class="card-label">([^<]+)</div>', dashboard_html)
files = []
external: list[str] = []
loopback: list[str] = []
for relative in (
"dashboard/static/index.html",
"dashboard/static/app.js",
"dashboard/static/style.css",
"playground/static/index.html",
"playground/static/app.js",
"playground/static/style.css",
"webui/static/webui.js",
"webui/static/webui.css",
):
path = root / relative
text = path.read_text()
files.append({"file": relative, "bytes": path.stat().st_size})
for hit in _OFF_HOST.findall(text):
# A loopback address is this machine, not a third party. The only
# one in the shipped files is the example endpoint printed inside
# the playground's copy-as-curl snippet, which is text on the page
# rather than something the browser fetches.
bucket = loopback if hit.startswith(("http://127.0.0.1", "http://localhost")) else external
bucket.append(f"{relative}: {hit}")
snippet_kinds = re.findall(r'class="snippet-tab[^"]*" data-kind="([a-z]+)"', playground_html)
modes = re.findall(r'name="mode" value="([a-z]+)"', playground_html)
return {
"dashboard": {
"panels": panels,
"summary_cards": summary_cards,
"data_endpoints": [
"/dashboard/data.json",
"/dashboard/spans",
"/dashboard/catalog.json",
"/dashboard/history.json",
"/dashboard/topology.json",
],
},
"playground": {"snippet_kinds": snippet_kinds, "modes": modes},
"static_files": files,
"static_bytes": sum(f["bytes"] for f in files),
# Zero is the claim `/dashboard` makes, and this is the number behind it.
"external_references": len(external),
"external_reference_list": external,
"loopback_references": loopback,
}
def _summary(obj) -> str:
"""The first sentence of a docstring, as one line."""
doc = (obj.__doc__ or "").strip()
if not doc:
return ""
first = doc.split("\n\n")[0]
return " ".join(first.split())
def _fields(cls) -> list[dict]:
"""A dataclass's fields, with the type and the default as written."""
import dataclasses
rows = []
for f in dataclasses.fields(cls):
if f.default is not dataclasses.MISSING:
default = repr(f.default)
elif f.default_factory is not dataclasses.MISSING: # type: ignore[misc]
default = None
else:
default = None
rows.append(
{
"name": f.name,
"type": str(f.type),
"default": default,
"required": f.default is dataclasses.MISSING
and f.default_factory is dataclasses.MISSING, # type: ignore[misc]
}
)
return rows
def collect_examples() -> dict:
"""The example programs that ship in the framework repository.
They are not part of the wheel — ``pyproject.toml`` excludes ``examples*``
from the packages it builds — so this reads the directory the CLI itself
resolves, through the CLI's own discovery function rather than a path
guessed here. Each row carries the first line of the script's docstring, the
provider or theme its directory groups it under, and whether the script
parses its own command-line arguments, which is what decides whether
``effgen examples run`` can start it.
"""
import ast
from effgen.cli.commands.examples import find_examples_dir
root = find_examples_dir()
if root is None:
raise RuntimeError(
"no examples directory found; run this from a checkout of the "
"framework, or set EFFGEN_EXAMPLES_DIR"
)
groups = {
"basic": "The shortest path — one agent, one question",
"tools": "Agents that call tools",
"advanced": "Streaming, memory, concurrency and multi-agent pipelines",
"web_retrieval": "The web, the weather and retrieval over your own files",
"plugins_presets": "Presets, and a tool you wrote yourself",
"openai": "OpenAI, including the native provider tools",
"cerebras": "Cerebras, on its free tier",
"data": "Fetching the data another example reads",
"utils": "Sweeping a model across settings",
}
items = []
for path in sorted(root.rglob("*.py")):
if path.name == "__init__.py":
continue
source = path.read_text(encoding="utf-8", errors="replace")
try:
docstring = ast.get_docstring(ast.parse(source)) or ""
except SyntaxError:
docstring = ""
summary = ""
for line in docstring.splitlines():
line = line.strip()
if line and not line.lower().startswith("effgen —"):
summary = line
break
relative = path.relative_to(root).with_suffix("").as_posix()
items.append(
{
"name": relative,
"group": relative.split("/")[0],
"file": f"examples/{path.relative_to(root).as_posix()}",
"summary": summary,
"parses_arguments": "argparse" in source,
"needs_key": relative.split("/")[0] in ("openai", "cerebras"),
}
)
counts: dict[str, int] = {}
for item in items:
counts[item["group"]] = counts.get(item["group"], 0) + 1
return {
"count": len(items),
"groups": [
{"id": group, "what": groups.get(group, ""), "count": counts[group]}
for group in sorted(counts)
],
"parses_arguments": sum(1 for item in items if item["parses_arguments"]),
"items": items,
}
def collect_api() -> dict:
"""The library surface `/agents` documents, read off the classes themselves.
Every parameter name, type and default on that page is a row from here, so
a default that changes in the framework changes the page rather than
silently disagreeing with it.
"""
import inspect
from effgen import (
AgentConfig,
AgentMiddleware,
CheckpointStore,
DropOldest,
FileCheckpointStore,
InMemoryCheckpointStore,
KeepFirstAndLast,
KeepToolResults,
LoggingMiddleware,
OrchestrationPattern,
SummarizeOldest,
ToolApprovalMiddleware,
ToolCall,
ToolCallList,
)
from effgen.core.agent import AgentResponse
from effgen.tools.base_tool import ToolResult
hooks = [
"before_run",
"after_run",
"before_model_call",
"after_model_call",
"before_tool_call",
"after_tool_call",
]
return {
"agent_config": _fields(AgentConfig),
"agent_response": _fields(AgentResponse),
"tool_call": _fields(ToolCall),
"tool_call_list": sorted(
name
for name in ("names", "failed", "total", "by_name", "to_list")
if hasattr(ToolCallList(), name)
),
"tool_result": _fields(ToolResult),
"middleware_hooks": [
{
"name": hook,
"signature": str(inspect.signature(getattr(AgentMiddleware, hook))).replace(
"self, ", ""
),
"what": _summary(getattr(AgentMiddleware, hook)),
}
for hook in hooks
],
"middleware_shipped": [
{"name": cls.__name__, "what": _summary(cls)}
for cls in (LoggingMiddleware, ToolApprovalMiddleware)
],
"compaction": [
{
"name": cls.__name__,
"what": _summary(cls),
"parameters": [
{
"name": name,
"default": (
repr(param.default)
if param.default is not inspect.Parameter.empty
else None
),
}
for name, param in inspect.signature(cls.__init__).parameters.items()
if name != "self"
],
}
for cls in (SummarizeOldest, DropOldest, KeepFirstAndLast, KeepToolResults)
],
"checkpoint_stores": [
{"name": cls.__name__, "what": _summary(cls)}
for cls in (FileCheckpointStore, InMemoryCheckpointStore, CheckpointStore)
],
"orchestration_patterns": [pattern.value for pattern in OrchestrationPattern],
}
def collect_production() -> dict:
"""The operational surface `/production` documents.
The roles, the metric names and the error classes are read from the
installed server and observability modules — not from the documentation,
which is a separate artefact and can lag behind the code.
"""
import dataclasses
import importlib
from effgen import get_guardrail_preset
from effgen import RateLimitExceeded
from effgen.models import errors as model_errors
rbac = importlib.import_module("effgen.server.rbac")
metrics = importlib.import_module("effgen.observability.metrics")
roles = []
for role in rbac.list_roles():
row = dataclasses.asdict(role) if dataclasses.is_dataclass(role) else dict(role)
roles.append(
{
"name": row["name"],
"tools": "none" if row.get("deny_tools") else "all",
"models": sorted(row["allowed_models"]) or "all",
"max_cost_per_day": row["max_cost_per_day"],
}
)
instruments = []
for attribute in sorted(dir(metrics)):
instrument = getattr(metrics, attribute)
name = getattr(instrument, "name", None)
if not isinstance(name, str) or not name.startswith("effgen_"):
continue
instruments.append(
{
"name": name,
"kind": type(instrument).__name__.replace("Labeled", "").lower(),
"help": getattr(instrument, "help", ""),
"labels": list(getattr(instrument, "label_names", ()) or []),
}
)
instruments.sort(key=lambda row: row["name"])
guardrail_presets = []
for name in ("minimal", "standard", "strict", "phi"):
chain = get_guardrail_preset(name)
guardrail_presets.append(
{"name": name, "guardrails": [g.name for g in chain.guardrails]}
)
# What each typed error is classified as, by running the real classifier
# over one instance of each — so the table is the behaviour, not a summary
# of it.
error_classes = []
for cls in (
model_errors.ModelAuthError,
model_errors.ModelNotFoundError,
RateLimitExceeded,
model_errors.ModelTimeoutError,
model_errors.ProviderTransientError,
model_errors.ModelRefusalError,
model_errors.InvalidRequestError,
model_errors.BackendUnreachableError,
):
classified = model_errors.classify_provider_error(cls("x"))
error_classes.append(
{
"name": cls.__name__,
"category": classified.category,
"should_retry": bool(classified.should_retry),
}
)
return {
"rbac_roles": roles,
"metrics": instruments,
"guardrail_presets": guardrail_presets,
"guardrail_positions": [
position.value
for position in importlib.import_module("effgen.guardrails").GuardrailPosition
],
"error_classes": error_classes,
"remediation_categories": list(model_errors.REMEDIATION_BY_CATEGORY),
"public_endpoints": sorted(
{
"/health",
"/healthz",
"/livez",
"/ready",
"/readyz",
"/slo",
"/openapi.json",
"/docs",
"/redoc",
}
),
}
def collect() -> dict:
data: dict = {
"_comment": (
"Generated by scripts/gen_site_data.py from the installed effGen "
"package. Do not edit by hand — regenerate it. Every count the site "
"shows comes from here."
),
"derived_at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
}
data.update(collect_version())
data.update(collect_public_surface())
data["tools"] = collect_tools()
data["presets"] = collect_presets()
data["prompts"] = collect_prompts()
data["models"] = collect_models()
data["cli"] = collect_cli()
data["code"] = collect_code()
data["web"] = collect_web()
data["examples"] = collect_examples()
data["api"] = collect_api()
data["production"] = collect_production()
return data
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument(
"--check",
action="store_true",
help="exit 1 if the checked-in file differs from a fresh derivation",
)
ap.add_argument(
"--stdout", action="store_true", help="print the JSON and write nothing"
)
args = ap.parse_args()
fresh = collect()
text = json.dumps(fresh, indent=2, sort_keys=False) + "\n"
if args.stdout:
sys.stdout.write(text)
return 0
if args.check:
if not OUT.exists():
print(f"{OUT.relative_to(REPO)} does not exist", file=sys.stderr)
return 1
current = json.loads(OUT.read_text())
a = {k: v for k, v in current.items() if k != "derived_at"}
b = {k: v for k, v in fresh.items() if k != "derived_at"}
if a != b:
changed = sorted(
k for k in set(a) | set(b) if a.get(k) != b.get(k)
)
print(
f"{OUT.relative_to(REPO)} is stale; these differ: "
f"{', '.join(changed)}",
file=sys.stderr,
)
return 1
print(f"{OUT.relative_to(REPO)} matches the installed framework")
return 0
OUT.parent.mkdir(parents=True, exist_ok=True)
OUT.write_text(text)
print(f"wrote {OUT.relative_to(REPO)}")
print(f" version {fresh['version']}")
print(f" public names {fresh['public_names']}")
print(f" tools {fresh['tools']['count']}"
f" in {len(fresh['tools']['categories'])} categories")
print(f" presets {fresh['presets']['count']}")
print(f" prompt templates {fresh['prompts']['templates']}"
f" ({fresh['prompts']['library']} in the library,"
f" {len(fresh['prompts']['domains'])} domains)")
print(f" provider adapters {fresh['models']['adapter_count']}"
f" ({fresh['models']['with_catalog_count']} with a bundled catalog)")
print(f" catalogued models {fresh['models']['models']}")
print(f" CLI commands {fresh['cli']['command_count']}"
f" + {fresh['cli']['subcommand_count']} sub-commands")
print(f" example programs {fresh['examples']['count']}"
f" in {len(fresh['examples']['groups'])} directories"
f" ({fresh['examples']['parses_arguments']} parse their own arguments)")
return 0
if __name__ == "__main__":
raise SystemExit(main())
#!/usr/bin/env python3
"""Derive every count and list the website states, straight from the installed
effGen package, and write them to ``data/effgen.json``.
The site used to type its numbers into JSX, which is how it came to advertise a
tool count, a model count and a version that the framework had moved past. This
script is the replacement: one file on disk, generated by one command, imported
by both codebases.
python scripts/gen_site_data.py # write data/effgen.json
python scripts/gen_site_data.py --check # exit 1 if it is stale
python scripts/gen_site_data.py --stdout # print, write nothing
Everything here is introspected from the live package or parsed out of the real
``--help`` output, so it cannot drift from what is installed. The one figure that
is a snapshot rather than a computation is the model catalog, which ships with
the package; ``effgen models refresh`` updates it.
Run it with the framework's environment on PATH::
export PATH=/path/to/your/effgen/env/bin:$PATH # or activate it however you do
unset EFFGEN_BASE_URL OPENAI_BASE_URL OPENAI_API_BASE
python scripts/gen_site_data.py
``--check`` is what CI and the verification wave run: it regenerates in memory
and compares against the checked-in file, ignoring ``derived_at``, so a stale
count fails the build instead of reaching a page.
"""
from __future__ import annotations
import argparse
import json
import re
import subprocess
import sys
from datetime import datetime, timezone
from pathlib import Path
REPO = Path(__file__).resolve().parent.parent
OUT = REPO / "data" / "effgen.json"
# Local inference engines. These are not provider adapters — they run weights on
# the machine effGen is running on — so they are listed separately everywhere the
# site talks about "where a model can come from".
LOCAL_ENGINES = ["transformers", "vllm", "gguf", "mlx"]
def _cli(*args: str) -> str:
"""Run the real `effgen` binary and return its stdout."""
proc = subprocess.run(
["effgen", *args],
capture_output=True,
text=True,
timeout=120,
)
if proc.returncode != 0 and not proc.stdout:
raise RuntimeError(f"effgen {' '.join(args)} failed: {proc.stderr[:400]}")
return proc.stdout
def collect_version() -> dict:
from importlib.metadata import metadata, version
meta = metadata("effgen")
classifiers = meta.get_all("Classifier") or []
pythons = sorted(
c.rsplit(":", 1)[1].strip()
for c in classifiers
if c.startswith("Programming Language :: Python :: 3.")
)
return {
"version": version("effgen"),
"python_versions": pythons,
"python_requires": meta.get("Requires-Python", ""),
}
def collect_public_surface() -> dict:
import effgen
return {"public_names": len(effgen.__all__)}
def _example_arguments(md) -> tuple[dict, str]:
"""The arguments to show in a tool's snippet, taken from the tool itself.
A tool's metadata carries its own worked examples, and where it does, the
first one is the call the gallery shows — the values come from whoever wrote
the tool, not from whoever wrote the page. Those examples also carry the
output they produced, under an ``output`` key; that is illustrative and is
dropped here, because the site shows output it ran for itself or none at
all.
A tool with no example falls back to its required parameters, filled from
the schema: the first allowed value of an enum, or a placeholder named after
the type. The second return value says which of the two happened, so the
page can mark a snippet whose arguments are placeholders rather than
presenting it as a call that would run.
"""
Xet Storage Details
- Size:
- 39.4 kB
- Xet hash:
- 8ab2aa6f1551dc0baa7a693ff09e28f9a1b25935f2e9e20b122e24f081508fea
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.