-
Notifications
You must be signed in to change notification settings - Fork 10
feat(python-sdk): telemetry #71
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
czi-fsisenda
wants to merge
3
commits into
main
Choose a base branch
from
fsisenda/sdk_python_telemetry
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
69 changes: 69 additions & 0 deletions
69
sdks/python/src/learning_commons_evaluators/schemas/ts_telemetry.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,69 @@ | ||
| """Wire types aligned with ``sdks/typescript/src/telemetry/types.ts``. | ||
|
|
||
| Hand-maintained; keep in sync with the TypeScript SDK until a shared schema exists. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from typing import Literal | ||
|
|
||
| from pydantic import BaseModel, ConfigDict | ||
|
|
||
| __all__ = [ | ||
| "EvaluationTelemetryStatus", | ||
| "TelemetryEvent", | ||
| "TelemetryMetadataPayload", | ||
| "TelemetryStageDetail", | ||
| "TelemetryTokenUsage", | ||
| ] | ||
|
|
||
| # Mirrors TS ``EvaluationStatus`` | ||
| EvaluationTelemetryStatus = Literal["success", "error"] | ||
|
|
||
|
|
||
| class TelemetryTokenUsage(BaseModel): | ||
| """Mirrors TS ``TokenUsage``.""" | ||
|
|
||
| model_config = ConfigDict(extra="forbid") | ||
|
|
||
| input_tokens: int | ||
| output_tokens: int | ||
|
|
||
|
|
||
| class TelemetryStageDetail(BaseModel): | ||
| """Mirrors TS ``StageDetail``.""" | ||
|
|
||
| model_config = ConfigDict(extra="forbid") | ||
|
|
||
| stage: str | ||
| provider: str | ||
| latency_ms: float | ||
| token_usage: TelemetryTokenUsage | None = None | ||
| schema_validation_failed: bool | None = None | ||
|
|
||
|
|
||
| class TelemetryMetadataPayload(BaseModel): | ||
| """Mirrors TS ``TelemetryMetadata``.""" | ||
|
|
||
| model_config = ConfigDict(extra="forbid") | ||
|
|
||
| stage_details: list[TelemetryStageDetail] | None = None | ||
|
|
||
|
|
||
| class TelemetryEvent(BaseModel): | ||
| """Mirrors TS ``TelemetryEvent`` (JSON field names match the TS interface).""" | ||
|
|
||
| model_config = ConfigDict(extra="forbid") | ||
|
|
||
| timestamp: str | ||
| sdk_version: str | ||
| evaluator_type: str | ||
| grade: str | None = None | ||
| status: EvaluationTelemetryStatus | ||
| error_code: str | None = None | ||
| latency_ms: float | ||
| text_length_chars: int | ||
| provider: str | ||
| token_usage: TelemetryTokenUsage | None = None | ||
| metadata: TelemetryMetadataPayload | None = None | ||
| input_text: str | None = None |
121 changes: 121 additions & 0 deletions
121
sdks/python/src/learning_commons_evaluators/telemetry/__init__.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,121 @@ | ||
| """Telemetry: schedule and send evaluation events (fire-and-forget HTTP POST).""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import asyncio | ||
| import threading | ||
| import uuid | ||
| from concurrent.futures import ThreadPoolExecutor | ||
| from datetime import datetime, timezone | ||
|
|
||
| import httpx | ||
|
|
||
| from learning_commons_evaluators.schemas.config import EvaluatorConfig | ||
| from learning_commons_evaluators.schemas.evaluator import EvaluationInput | ||
| from learning_commons_evaluators.schemas.metadata import EvaluationMetadata | ||
| from learning_commons_evaluators.telemetry.adapter import evaluation_to_typescript_telemetry_event | ||
| from learning_commons_evaluators.telemetry.utils import client_id_from_seed, iso_utc_z | ||
|
|
||
| __all__ = [ | ||
| "evaluation_to_typescript_telemetry_event", | ||
| "schedule_send_telemetry", | ||
| "send_telemetry", | ||
| "should_send_telemetry", | ||
| ] | ||
|
|
||
| _TELEMETRY_EXECUTOR: ThreadPoolExecutor | None = None | ||
| _TELEMETRY_EXECUTOR_LOCK = threading.Lock() | ||
|
|
||
|
|
||
| def _get_telemetry_executor() -> ThreadPoolExecutor: | ||
| global _TELEMETRY_EXECUTOR | ||
| with _TELEMETRY_EXECUTOR_LOCK: | ||
| if _TELEMETRY_EXECUTOR is None: | ||
| _TELEMETRY_EXECUTOR = ThreadPoolExecutor( | ||
| max_workers=2, | ||
| thread_name_prefix="lc-telemetry", | ||
| ) | ||
| return _TELEMETRY_EXECUTOR | ||
|
|
||
|
|
||
| def should_send_telemetry(config: EvaluatorConfig) -> bool: | ||
| """Return True when telemetry is configured with a non-empty partner / client id.""" | ||
| partner_id = config.telemetry.telemetry_partner_id | ||
| return bool(partner_id and partner_id.strip()) | ||
|
|
||
|
|
||
| def _is_uuid(value: str | None) -> bool: | ||
| if value is None: | ||
| return False | ||
| try: | ||
| uuid.UUID(value) | ||
| return True | ||
| except (ValueError, TypeError, AttributeError): | ||
| return False | ||
|
|
||
|
|
||
| async def send_telemetry( | ||
| evaluation_metadata: EvaluationMetadata, | ||
| inp: EvaluationInput | None, | ||
| config: EvaluatorConfig, | ||
| ) -> None: | ||
| """POST a TypeScript-shaped telemetry JSON payload. Never raises to callers (logs failures).""" | ||
| if not should_send_telemetry(config): | ||
| return | ||
|
|
||
| try: | ||
| partner_id = config.telemetry.telemetry_partner_id | ||
| assert ( | ||
| partner_id is not None | ||
| ) # for mypy: ``should_send_telemetry`` guarantees non-empty after strip. | ||
| telemetry_partner_id = partner_id.strip() | ||
|
|
||
| event = evaluation_to_typescript_telemetry_event(evaluation_metadata, inp, config) | ||
| # TS SDK sets timestamp at send time (`new Date().toISOString()`), not evaluation start. | ||
| event = event.model_copy(update={"timestamp": iso_utc_z(datetime.now(timezone.utc))}) | ||
| payload = event.model_dump(mode="json", exclude_none=True) | ||
|
|
||
| api_key = telemetry_partner_id if not _is_uuid(telemetry_partner_id) else None | ||
| client_id = ( | ||
| telemetry_partner_id | ||
| if _is_uuid(telemetry_partner_id) | ||
| else client_id_from_seed(telemetry_partner_id, config.client_id_seed) | ||
| ) | ||
|
|
||
| headers: dict[str, str] = { | ||
| "Content-Type": "application/json", | ||
| "X-Client-ID": client_id, | ||
| } | ||
| if api_key is not None: | ||
| headers["X-API-Key"] = api_key | ||
|
|
||
| timeout = httpx.Timeout(5.0) | ||
| async with httpx.AsyncClient(timeout=timeout) as client: | ||
| response = await client.post(config.telemetry.endpoint, json=payload, headers=headers) | ||
| if response.is_error: | ||
| # Log status only; response bodies may echo input text or other sensitive data. | ||
| config.logger.warning( | ||
| "telemetry send failed: HTTP %s", | ||
| response.status_code, | ||
| ) | ||
| except Exception as e: | ||
| # Log exception type only; ``str(e)`` may include payload fields (e.g. input_text). | ||
| config.logger.warning( | ||
| "telemetry send failed: %s", | ||
| type(e).__qualname__, | ||
| ) | ||
|
|
||
|
|
||
| def schedule_send_telemetry( | ||
| evaluation_metadata: EvaluationMetadata, | ||
| inp: EvaluationInput | None, | ||
| config: EvaluatorConfig, | ||
| ) -> None: | ||
| """Fire-and-forget: run :func:`send_telemetry` on a shared worker when telemetry is enabled.""" | ||
| if not should_send_telemetry(config): | ||
| return | ||
|
|
||
| def _run() -> None: | ||
| asyncio.run(send_telemetry(evaluation_metadata, inp, config)) | ||
|
|
||
| _get_telemetry_executor().submit(_run) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
P0 - I would strongly recommend making the telemetry anonymous in the config by default, ie. not even needing to specify the config_config_anonymous_telemetry but just using create_config for the happy path default + primary documented case.
And then we can module-cache the
_ANONYMOUS_CLIENT_IDacross create_configs / Evals