* feat(observability): optional PostHog integration (errors, LLM traces, replay, flags)
Off by default. Activates when POSTHOG_API_KEY is set in env. Defaults
to PostHog Cloud EU; override host for US Cloud or self-hosted.
Coverage:
- FastAPI 500 handler captures unhandled exceptions
- src/orchestrator.py rebuild + rebuild_source failures
- services/scheduler/ HTTP-job failures
- cli/main.py uncaught CLI errors (Typer.Exit/SystemExit/KeyboardInterrupt
skipped; flushes before re-raise so short-lived CLI invocations don't
drop events)
- connectors/llm/anthropic_provider.py + openai_compat.py emit
$ai_generation events with provider, model, latency, token counts
(prompt/completion bodies stay off unless POSTHOG_LLM_PAYLOADS=1
because LLM prompts here routinely include customer SQL/data)
- Browser snippet injected into every text/html response by
PosthogInjectionMiddleware — registered inside the GZip layer so it
sees uncompressed HTML before compression. Many templates are
standalone (their own DOCTYPE) and never extend base.html, so a
per-template include would miss them.
- Frontend: $pageview, $pageleave, JS error capture via window.error
and unhandledrejection handlers, masked session replay
(maskAllInputs: true plus CSS-selector mask for known data surfaces),
feature flags (browser posthog.isFeatureEnabled + server-side
feature_enabled with fallback for older SDKs).
Identification mode operator-configurable: none / id / email / full.
Default email ships user.id + email but never name. CLI entry point
moves from cli.main:app to cli.main:main (Typer wrapper).
Files:
- src/observability/posthog_client.py — lazy singleton, no network
when disabled, single-process flush on shutdown
- src/observability/llm_tracing.py — trace_generation context manager
- app/middleware/posthog_inject.py — HTML rewrite middleware
- app/web/templates/_posthog.html — browser snippet template
- docs/observability.md — operator guide
- config/.env.template — documented POSTHOG_* knobs
- tests/test_posthog_disabled.py + tests/test_posthog_client.py +
tests/test_llm_tracing.py — 18 tests covering disabled state,
identify-mode payloads, $ai_generation shape, error variant.
CHANGELOG entry under [Unreleased] Added.
* feat(observability): tag every PostHog event with environment + release
Splits PostHog dashboards cleanly between localhost / dev / staging /
production without manual tagging on every capture call.
- POSTHOG_ENVIRONMENT explicit override; auto-resolves to "local" when
LOCAL_DEV_MODE=1, else RELEASE_CHANNEL, else AGNES_DEPLOYMENT_ENV,
else "unknown".
- AGNES_VERSION → RELEASE_CHANNEL fallback feeds the `release` property
for "is this error new in this release?" cohorting.
- Backend gets both via the PostHog SDK's super_properties constructor
arg (every captured event picks them up automatically).
- Browser snippet calls posthog.register({environment, release}) inside
the loaded callback so $pageview, $exception, autocapture, etc. all
carry the same labels.
- request.state.user now populated by auth dependencies so the snippet
can actually call posthog.identify(user_id, {email}) for logged-in
users (previously the user block always resolved to None because
nothing wrote to request.state.user).
4 new tests cover env resolution: explicit > LOCAL_DEV_MODE > channel
> unknown, plus super-properties forwarding into the SDK constructor.
* feat(observability): inline user attrs on every PostHog event + debug throw route
PostHog's UI shows person properties on the Person profile page, not
inline on each event — so a reviewer triaging an exception couldn't tell
which user hit the bug without clicking through. Fix it on both sides.
- Backend capture_exception merges user_id / user_email / user_name into
the event properties (gated by POSTHOG_IDENTIFY_PII: none/id/email/full).
Backed by a new _user_props_for_event helper on PosthogClient.
- Browser snippet registers user_id + user_email + user_name as super-
properties via posthog.register({...}) so every $exception, $pageview,
and custom event coming from posthog.captureException() carries them
inline. Mirrors the backend so cross-referencing client/server events
doesn't require a person-profile lookup.
- /api/debug/throw — debug-only endpoint gated by DEBUG=1 (404 in prod).
Runs Depends(get_current_user) first so request.state.user is set when
the unhandled-exception handler captures the event. Lets operators
exercise the full observability path end-to-end without hand-rolling
a TestClient script. Configurable via ?kind=ValueError&msg=...
7 new tests cover: backend user-attr merge across identify modes,
anonymous request fall-through, browser snippet super-prop emission for
logged-in / anonymous / id-only / full-name cases.
* fix(observability): address minasarustamyan PR #231 review
Two bugs caught in review.
1. PosthogInjectionMiddleware dropped Response.background on every
return path. BaseHTTPMiddleware materialises the body and asks
subclasses to return a fresh Response — three paths in dispatch()
omitted background=, silently cancelling any BackgroundTask /
BackgroundTasks the route attached (audit logging, async webhooks,
email sends) with no log line. Fix: route every return through a
_passthrough() helper that forwards background.
Also adds a _MAX_BUFFER_BYTES (4 MB) cap so a streamed-HTML response
can't balloon RSS during buffering. Bigger bodies short-circuit
through with a warning rather than being injected.
Regression tests in tests/test_posthog_inject_middleware.py exercise
four return paths (snippet present, render-fail, double-injection
guard, non-HTML passthrough) plus the streaming-guard short-circuit.
2. $ai_input / $ai_output_choices were emitted without truncation, so
POSTHOG_LLM_PAYLOADS=1 silently dropped events past PostHog's ~32 KB
per-event ingest limit — exactly the calls (large prompts with
schemas / sample rows / SQL) an operator would want to inspect.
Fix: clip both at POSTHOG_LLM_PAYLOAD_MAX_CHARS (default 30000) with
an explicit "…[truncated N chars]" marker so readers don't mistake
truncated captures for complete ones. Metadata (provider, model,
tokens, latency, error) flows regardless. Three new tests cover
default-cap clipping, env-override, and pass-through under the cap.
37 PostHog tests pass.
323 lines
11 KiB
Python
323 lines
11 KiB
Python
"""OpenAI-compatible provider for structured JSON extraction.
|
|
|
|
Supports any OpenAI-compatible API endpoint with progressive fallback
|
|
for structured output: json_schema -> json_object -> prompt-based JSON.
|
|
"""
|
|
|
|
import json
|
|
import logging
|
|
import re
|
|
import time
|
|
from urllib.parse import urlparse
|
|
|
|
import httpx
|
|
import openai
|
|
|
|
from .exceptions import (
|
|
LLMAuthError,
|
|
LLMFormatError,
|
|
LLMRateLimitError,
|
|
LLMRefusalError,
|
|
LLMTimeoutError,
|
|
LLMUnsupportedError,
|
|
)
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
# Retry configuration
|
|
MAX_RETRIES = 3
|
|
INITIAL_BACKOFF_SECONDS = 2
|
|
BACKOFF_MULTIPLIER = 2
|
|
|
|
# Regex to strip markdown code fences and extract JSON
|
|
_JSON_FENCE_PATTERN = re.compile(r"```(?:json)?\s*\n?(.*?)\n?\s*```", re.DOTALL)
|
|
|
|
|
|
def _sanitize_url(url: str) -> str:
|
|
"""Extract scheme://host from a URL for safe logging.
|
|
|
|
Never logs path, query params, or fragments which may contain
|
|
tokens or sensitive information.
|
|
"""
|
|
parsed = urlparse(url)
|
|
return f"{parsed.scheme}://{parsed.netloc}"
|
|
|
|
|
|
def _extract_json_from_text(text: str) -> dict:
|
|
"""Parse JSON from potentially markdown-wrapped text.
|
|
|
|
Tries direct parsing first, then strips markdown code fences,
|
|
then falls back to finding content between first { and last }.
|
|
|
|
Raises:
|
|
LLMFormatError: If no valid JSON can be extracted.
|
|
"""
|
|
# Try direct parse first
|
|
stripped = text.strip()
|
|
try:
|
|
return json.loads(stripped)
|
|
except json.JSONDecodeError:
|
|
pass
|
|
|
|
# Try stripping markdown code fences
|
|
fence_match = _JSON_FENCE_PATTERN.search(stripped)
|
|
if fence_match:
|
|
try:
|
|
return json.loads(fence_match.group(1).strip())
|
|
except json.JSONDecodeError:
|
|
pass
|
|
|
|
# Fallback: find JSON between first { and last }
|
|
first_brace = stripped.find("{")
|
|
last_brace = stripped.rfind("}")
|
|
if first_brace != -1 and last_brace > first_brace:
|
|
try:
|
|
return json.loads(stripped[first_brace:last_brace + 1])
|
|
except json.JSONDecodeError:
|
|
pass
|
|
|
|
raise LLMFormatError(f"Could not extract valid JSON from model response")
|
|
|
|
|
|
class OpenAICompatExtractor:
|
|
"""Structured JSON extractor for OpenAI-compatible APIs.
|
|
|
|
Supports progressive fallback for structured output based on the
|
|
configured strategy:
|
|
- "strict": json_schema only, raises LLMUnsupportedError if not supported
|
|
- "json": json_schema -> json_object fallback
|
|
- "auto": json_schema -> json_object -> prompt-based JSON (default)
|
|
"""
|
|
|
|
def __init__(
|
|
self,
|
|
api_key: str,
|
|
base_url: str,
|
|
model: str,
|
|
structured_output: str = "auto",
|
|
verify_ssl: bool = True,
|
|
) -> None:
|
|
"""Initialize the OpenAI-compatible extractor.
|
|
|
|
Args:
|
|
api_key: API key for authentication.
|
|
base_url: Base URL of the OpenAI-compatible API.
|
|
model: Model identifier.
|
|
structured_output: Fallback strategy - "strict", "json", or "auto".
|
|
verify_ssl: Whether to verify SSL certificates. Set to False for
|
|
corporate proxies with self-signed certificates.
|
|
"""
|
|
# Custom httpx client for SSL control (corporate proxies often use self-signed certs)
|
|
http_client = httpx.Client(verify=verify_ssl)
|
|
self._client = openai.OpenAI(
|
|
api_key=api_key, base_url=base_url, http_client=http_client,
|
|
)
|
|
self._model = model
|
|
self._structured_output = structured_output
|
|
self._safe_url = _sanitize_url(base_url)
|
|
|
|
# Suppress OpenAI SDK and HTTP client debug logging which dumps full
|
|
# request bodies including prompt content — this is a security requirement
|
|
for noisy_logger in ("openai", "httpx", "httpcore"):
|
|
logging.getLogger(noisy_logger).setLevel(logging.WARNING)
|
|
|
|
def extract_json(
|
|
self,
|
|
prompt: str,
|
|
max_tokens: int,
|
|
json_schema: dict,
|
|
schema_name: str,
|
|
) -> dict:
|
|
"""Extract structured JSON using an OpenAI-compatible API.
|
|
|
|
Attempts structured output strategies in order of preference,
|
|
falling back as allowed by the configured strategy.
|
|
|
|
Args:
|
|
prompt: The extraction prompt to send to the model.
|
|
max_tokens: Maximum tokens in the response.
|
|
json_schema: JSON Schema that the response must conform to.
|
|
schema_name: Human-readable name for the schema.
|
|
|
|
Returns:
|
|
Parsed JSON dictionary conforming to the provided schema.
|
|
|
|
Raises:
|
|
LLMAuthError: Invalid API key.
|
|
LLMRateLimitError: Rate limited after all retries.
|
|
LLMTimeoutError: Timeout/connection error after all retries.
|
|
LLMFormatError: Response is not valid JSON.
|
|
LLMRefusalError: Model refused to respond.
|
|
LLMUnsupportedError: Required feature not supported and no fallback allowed.
|
|
"""
|
|
strategies = self._get_strategies()
|
|
|
|
for strategy in strategies:
|
|
try:
|
|
logger.info(
|
|
"OpenAI-compat extraction: url=%s, model=%s, strategy=%s, schema=%s",
|
|
self._safe_url, self._model, strategy, schema_name,
|
|
)
|
|
return self._extract_with_strategy(
|
|
prompt, max_tokens, json_schema, schema_name, strategy,
|
|
)
|
|
except LLMUnsupportedError:
|
|
logger.info(
|
|
"Strategy %s not supported at %s, trying next fallback",
|
|
strategy, self._safe_url,
|
|
)
|
|
continue
|
|
|
|
raise LLMUnsupportedError(
|
|
f"No supported structured output strategy for {self._safe_url} "
|
|
f"with configured mode '{self._structured_output}'"
|
|
)
|
|
|
|
def _get_strategies(self) -> list[str]:
|
|
"""Get ordered list of strategies to try based on configuration."""
|
|
if self._structured_output == "strict":
|
|
return ["json_schema"]
|
|
elif self._structured_output == "json":
|
|
return ["json_schema", "json_object"]
|
|
else: # "auto"
|
|
return ["json_schema", "json_object", "text"]
|
|
|
|
def _extract_with_strategy(
|
|
self,
|
|
prompt: str,
|
|
max_tokens: int,
|
|
json_schema: dict,
|
|
schema_name: str,
|
|
strategy: str,
|
|
) -> dict:
|
|
"""Execute extraction with a specific structured output strategy."""
|
|
last_exception: Exception | None = None
|
|
|
|
for attempt in range(1, MAX_RETRIES + 1):
|
|
try:
|
|
return self._attempt_extraction(
|
|
prompt, max_tokens, json_schema, schema_name,
|
|
strategy, attempt,
|
|
)
|
|
except LLMAuthError:
|
|
raise
|
|
except LLMRefusalError:
|
|
raise
|
|
except LLMUnsupportedError:
|
|
raise
|
|
except (LLMRateLimitError, LLMTimeoutError) as e:
|
|
last_exception = e
|
|
if attempt < MAX_RETRIES:
|
|
delay = INITIAL_BACKOFF_SECONDS * (BACKOFF_MULTIPLIER ** (attempt - 1))
|
|
logger.warning(
|
|
"Transient error on attempt %d/%d for %s model %s, "
|
|
"retrying in %ds: %s",
|
|
attempt, MAX_RETRIES, self._safe_url,
|
|
self._model, delay, type(e).__name__,
|
|
)
|
|
time.sleep(delay)
|
|
|
|
raise last_exception # type: ignore[misc]
|
|
|
|
def _attempt_extraction(
|
|
self,
|
|
prompt: str,
|
|
max_tokens: int,
|
|
json_schema: dict,
|
|
schema_name: str,
|
|
strategy: str,
|
|
attempt: int,
|
|
) -> dict:
|
|
"""Single extraction attempt with a specific strategy."""
|
|
logger.info(
|
|
"OpenAI-compat attempt %d/%d, url=%s, model=%s, strategy=%s",
|
|
attempt, MAX_RETRIES, self._safe_url, self._model, strategy,
|
|
)
|
|
|
|
messages = [{"role": "user", "content": prompt}]
|
|
kwargs: dict = {
|
|
"model": self._model,
|
|
"max_tokens": max_tokens,
|
|
"messages": messages,
|
|
}
|
|
|
|
if strategy == "json_schema":
|
|
kwargs["response_format"] = {
|
|
"type": "json_schema",
|
|
"json_schema": {
|
|
"name": schema_name,
|
|
"strict": True,
|
|
"schema": json_schema,
|
|
},
|
|
}
|
|
elif strategy == "json_object":
|
|
kwargs["response_format"] = {"type": "json_object"}
|
|
elif strategy == "text":
|
|
# Append JSON instruction to prompt for text-based fallback
|
|
messages = [
|
|
{
|
|
"role": "user",
|
|
"content": prompt + "\n\nIMPORTANT: Respond with valid JSON only, no markdown.",
|
|
},
|
|
]
|
|
kwargs["messages"] = messages
|
|
|
|
from src.observability import trace_generation
|
|
|
|
try:
|
|
with trace_generation(provider="openai_compat", model=self._model) as _trace:
|
|
_trace.set_input(prompt)
|
|
response = self._client.chat.completions.create(**kwargs)
|
|
_trace.set_output_from_openai(response)
|
|
except openai.AuthenticationError as e:
|
|
raise LLMAuthError(
|
|
f"OpenAI-compat authentication failed at {self._safe_url} (check API key)"
|
|
) from e
|
|
except openai.RateLimitError as e:
|
|
raise LLMRateLimitError(
|
|
f"OpenAI-compat rate limited at {self._safe_url}"
|
|
) from e
|
|
except (openai.APITimeoutError, openai.APIConnectionError) as e:
|
|
raise LLMTimeoutError(
|
|
f"OpenAI-compat connection error at {self._safe_url} ({type(e).__name__})"
|
|
) from e
|
|
except openai.BadRequestError as e:
|
|
# json_schema format not supported by this endpoint
|
|
error_msg = str(e).lower()
|
|
if "response_format" in error_msg or "json_schema" in error_msg:
|
|
raise LLMUnsupportedError(
|
|
f"Structured output strategy '{strategy}' not supported "
|
|
f"at {self._safe_url}"
|
|
) from e
|
|
raise LLMFormatError(
|
|
f"Bad request at {self._safe_url} ({type(e).__name__})"
|
|
) from e
|
|
|
|
choice = response.choices[0]
|
|
|
|
# Check for truncation - raise and let outer retry loop handle it
|
|
if choice.finish_reason == "length":
|
|
raise LLMFormatError(
|
|
f"Response truncated (max_tokens) for schema {schema_name} "
|
|
f"at {self._safe_url}"
|
|
)
|
|
|
|
# Check for refusal
|
|
content = choice.message.content
|
|
if not content:
|
|
raise LLMRefusalError(
|
|
f"Model at {self._safe_url} refused to generate response "
|
|
f"for schema {schema_name}"
|
|
)
|
|
|
|
# Parse JSON from response
|
|
if strategy == "text":
|
|
return _extract_json_from_text(content)
|
|
|
|
try:
|
|
return json.loads(content)
|
|
except json.JSONDecodeError as e:
|
|
raise LLMFormatError(
|
|
f"Failed to parse response as JSON for schema {schema_name} "
|
|
f"at {self._safe_url} ({type(e).__name__})"
|
|
) from e
|