Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion src/rius/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,19 @@

__version__ = "1.5.5" # x-release-please-version

from .client import GlassflowClient, build_span_exporter, get_tracer, init, register_workspace
from .client import (
GlassflowClient,
build_span_exporter,
drain_hints,
get_tracer,
init,
register_workspace,
)
from .compaction import mark_compaction
from .config import GlassflowConfig, resolve_config
from .export_health import ProbeTransport
from .generation import Generation, start_as_current_generation, start_generation
from .hints import Hint
from .observe import observe
from .semconv import SpanKind
from .session import session
Expand All @@ -18,11 +26,13 @@
"Generation",
"GlassflowClient",
"GlassflowConfig",
"Hint",
"Observation",
"ProbeTransport",
"SpanKind",
"__version__",
"build_span_exporter",
"drain_hints",
"get_tracer",
"init",
"mark_compaction",
Expand Down
86 changes: 85 additions & 1 deletion src/rius/_semconv_generated.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Vendored from rius-semconv v1.10.0 out/python/_semconv_generated.py by
# Vendored from rius-semconv v1.11.0 out/python/_semconv_generated.py by
# scripts/sync-semconv.sh. Do not edit: change the registry in rius-semconv.
"""Rius semantic conventions: the constants and tables, generated.

Expand Down Expand Up @@ -610,6 +610,53 @@
# the OpenTelemetry naming rules do not allow for an attribute.
RIUS_COMPACTION_SUMMARY_TEXT = "rius.compaction.summary.text"

# --- Agent hints ---
# A hint is a short note Rius sends to a running agent about a problem it
# detected in the agent's current run ("search_docs has returned 0 results
# 5 times in this run; lookup_index covers the same pages"). The SDK
# receives it on the heartbeat response and hands it to the agent: the
# agent's code pulls it, an on_hint callback receives it, or a framework
# hook adds it to the next model call. The rius.hint.* keys are the
# attributes of the rius.hint.delivered event the SDK records at that
# moment, and are never set on a span. No convention defines a hint or
# its delivery.
# The hint's id exactly as Rius sent it, the same on every redelivery. It
# is the join key to the record Rius keeps for each hint it writes, which
# holds the run the hint is about, its code, the text the agent received
# and when it was written, so a reader finds what the hint said and how
# long it took to arrive without the event repeating any of it.
# The SDK de-duplicates on the id, so a hint Rius sends again gives no
# second event on the same channel. A hint can reach the agent through
# more than one channel and gives one event for each: at most one per
# (rius.hint.id, rius.hint.channel). A count of hints delivered must
# deduplicate on rius.hint.id.
RIUS_HINT_ID = "rius.hint.id"

# Which problem the hint is about, as Rius named it. Copied from the hint
# so that measuring whether hints help can group deliveries by detector
# straight from the trace. The SDK copies it and never interprets it.
# Not gen_ai.prompt.name: a hint is not a managed prompt, and the model
# call a hint is injected into may carry the agent's own
# gen_ai.prompt.name and gen_ai.prompt.version, naming that call's prompt.
RIUS_HINT_CODE = "rius.hint.code"

# Each code's wording is versioned, and a change of wording bumps the
# version, so two wordings of the same hint can be compared. An int, as
# Rius sends it. Not gen_ai.prompt.version, for the reason given on
# rius.hint.code.
RIUS_HINT_TEMPLATE_VERSION = "rius.hint.template_version"

# drain when the agent's own code pulled the hint (drain_hints()),
# callback when the SDK passed it to an on_hint callback, inject when a
# framework hook added it to a model call just before the call. Only
# inject guarantees the model saw the hint; with drain and callback the
# agent's code decides what to do with it. Measuring whether hints help
# needs to tell the two apart.
RIUS_HINT_CHANNEL = "rius.hint.channel"
RIUS_HINT_CHANNEL_DRAIN = "drain"
RIUS_HINT_CHANNEL_CALLBACK = "callback"
RIUS_HINT_CHANNEL_INJECT = "inject"

# --- Span event names ---
# Deprecated: replaced by the gen_ai.response.time_to_first_chunk span attribute.
# First streamed token/chunk arrived. The standard signal is the span
Expand All @@ -633,6 +680,35 @@
# compacted context sets gen_ai.conversation.compacted.
RIUS_COMPACTION_EVENT = "rius.compaction"

# Recorded when the SDK hands a hint to the agent: drain_hints() returns
# it, an on_hint callback receives it, or a framework hook adds it to a
# model call. For every channel, the event goes on the root span of the
# run the hint is about (the hint's trace_id). The SDK keeps each run's
# root span while the run is open, and Rius delivers a hint only while
# its run is open. A hint with no trace_id is about the instance as a
# whole: its event goes on the current span if one is recording, and
# otherwise no event is recorded.
# One run can get several hints, so its root span can carry several of
# these events, one per hint and channel: at most one per
# (rius.hint.id, rius.hint.channel). A count of hints delivered must
# deduplicate on rius.hint.id.
# It carries the rius.hint.* attributes and never the hint's text, which
# the record Rius keeps for each hint it writes holds under the id.
# It records delivery, not the acknowledgement on the heartbeat: an ack
# only tells Rius to stop sending the hint, and the SDK acks hints it
# drops as well.
# For inject, nothing else is needed to measure whether a hint helped. The
# hint's run is the trace the event sits in, and the model calls after the
# hint are the LLM spans of that trace that start after the event's
# timestamp. The hint's id joins the event to the record Rius keeps for each
# hint it writes (its code, its run, when it was written). A key on each
# later model call naming the hints it carried would repeat what that join
# gives. With drain or callback, this event only says the agent's code
# received the hint: the SDK cannot know whether the code passed it to the
# model, acted on it itself, or ignored it, so measuring those needs a
# record from the agent's code.
RIUS_HINT_DELIVERED_EVENT = "rius.hint.delivered"

# --- Pending (partial) spans ---
# Marks the content-free snapshot exported at span START; the backend maps it
# to Finished=0 and the real span replaces it at end. This key knowingly bends
Expand Down Expand Up @@ -1741,6 +1817,14 @@ class SpanKind(str, Enum):
"RIUS_COMPACTION_TRIGGER_AUTO",
"RIUS_COMPACTION_TRIGGER_MANUAL",
"RIUS_CONTEXT_SIZES",
"RIUS_HINT_CHANNEL",
"RIUS_HINT_CHANNEL_CALLBACK",
"RIUS_HINT_CHANNEL_DRAIN",
"RIUS_HINT_CHANNEL_INJECT",
"RIUS_HINT_CODE",
"RIUS_HINT_DELIVERED_EVENT",
"RIUS_HINT_ID",
"RIUS_HINT_TEMPLATE_VERSION",
"RIUS_MAIN_AGENT_DESCRIPTION",
"RIUS_MAIN_AGENT_ID",
"RIUS_MAIN_AGENT_NAME",
Expand Down
98 changes: 96 additions & 2 deletions src/rius/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@
ResourceAdoptingExporter,
bridge,
)
from .heartbeat import HeartbeatSender, OpenRootSpanTracker
from .heartbeat import HeartbeatSender, OpenRootSpanTracker, mint_instance_identity
from .hints import Hint, HintInbox, current_trace_id
from .instrumentation import enable_instrumentations, instruments_for
from .instrumentation import release as release_instrumentations
from .masking import MaskingSpanExporter
Expand Down Expand Up @@ -222,8 +223,10 @@ def __init__(
connectivity_thread: threading.Thread | None = None,
routing: RoutingSpanExporter | None = None,
bridge: Bridge | None = None,
hints: HintInbox | None = None,
) -> None:
self._provider = provider
self._hints = hints
self._bridge = bridge
self.config = config
self._heartbeat = heartbeat
Expand All @@ -250,6 +253,18 @@ def register_workspace(self, alias: str, api_key: str) -> None:
)
self._routing.register(alias, api_key)

def drain_hints(self, trace_id: str | None = None) -> list[Hint]:
"""Remove and return the hints received for a run, oldest first.

Returns the hints for ``trace_id`` (default: the trace of the current
span context) plus the hints about the instance as a whole. Outside
any span, only the instance-wide ones. Always empty when hints are
off (``init(hints=True)`` / ``RIUS_HINTS`` turns them on).
"""
if self._hints is None:
return []
return self._hints.drain(trace_id if trace_id is not None else current_trace_id())

def get_tracer(self, name: str = TRACER_NAME) -> trace.Tracer:
"""Return a tracer bound to this client's provider.

Expand Down Expand Up @@ -315,6 +330,9 @@ def init(
span_exporter: SpanExporter | None = None,
heartbeat: bool | None = None,
heartbeat_interval: float | None = None,
hints: bool | None = None,
hints_per_trace: int | None = None,
on_hint: Callable[[Hint], object] | None = None,
agent_name: str | None = None,
main_agent_id: str | None = None,
main_agent_description: str | None = None,
Expand Down Expand Up @@ -389,6 +407,18 @@ def init(
heartbeat_interval: Seconds between pings (default 15, clamped to
``[5, 300]``). The server fixes stale at 30s and gone at 60s
since the last ping, so keep this well under 30s.
hints: Ask Rius for hints on the heartbeat response (``RIUS_HINTS``;
off by default). A hint is a short note about a problem Rius
detected in one of this process's open runs; read them with
``drain_hints()``. Needs the heartbeat and its default transport:
with a ``heartbeat_transport`` hints stay off.
hints_per_trace: The most hints accepted for one run
(``RIUS_HINTS_PER_TRACE``, default 3); later ones are dropped.
on_hint: Called once with each newly accepted ``Hint``, on a
dedicated daemon thread, so it can never delay a heartbeat. If it
falls behind, the oldest pending calls are skipped. An exception
it raises is logged, and the hint stays queued for
``drain_hints()`` either way.
agent_name: Identity both heartbeats and spans group under, stamped
on the resource as ``gen_ai.main_agent.name`` AND, unchanged, as
``gen_ai.agent.name``; defaults to ``service_name``. The
Expand Down Expand Up @@ -490,6 +520,9 @@ def init(
span_exporter=span_exporter,
heartbeat=heartbeat,
heartbeat_interval=heartbeat_interval,
hints=hints,
hints_per_trace=hints_per_trace,
on_hint=on_hint,
agent_name=agent_name,
main_agent_id=main_agent_id,
main_agent_description=main_agent_description,
Expand Down Expand Up @@ -645,6 +678,9 @@ def _do_init(
span_exporter: SpanExporter | None,
heartbeat: bool | None,
heartbeat_interval: float | None,
hints: bool | None,
hints_per_trace: int | None,
on_hint: Callable[[Hint], object] | None,
agent_name: str | None,
main_agent_id: str | None,
main_agent_description: str | None,
Expand All @@ -671,6 +707,8 @@ def _do_init(
capture_content=capture_content,
heartbeat=heartbeat,
heartbeat_interval=heartbeat_interval,
hints=hints,
hints_per_trace=hints_per_trace,
agent_name=agent_name,
main_agent_id=main_agent_id,
main_agent_description=main_agent_description,
Expand All @@ -689,7 +727,16 @@ def _do_init(
# spans keep this (ancestor) id while its heartbeat re-arms with a fresh
# one; deployments needing exact per-worker span identity should init()
# after fork.
instance_id = str(uuid.uuid4())
# Derived from a per-instance secret the heartbeat presents, so another
# holder of the workspace key cannot ping as this instance. A custom
# transport is handed the payload only and could never send the secret,
# so it pings as a legacy instance: liveness as before, never hints.
instance_id: str
instance_secret: str | None
if heartbeat_transport is None:
instance_id, instance_secret = mint_instance_identity()
else:
instance_id, instance_secret = str(uuid.uuid4()), None
agent_name = _agent.named_agent(config.agent_name)
# telemetry.sdk.* is reserved for the OTel SDK itself (Resource.create fills
# it); we identify as a distribution via telemetry.distro.*.
Expand Down Expand Up @@ -867,18 +914,31 @@ def _do_init(
"rius heartbeat not started: no credentials (set api_key or an "
"Authorization header in headers)"
)
inbox: HintInbox | None = None
hints_off_because = _why_hints_are_off(config, heartbeat_transport, can_authenticate)
if config.hints and hints_off_because is not None:
logger.warning("rius hints were requested but are off: %s", hints_off_because)
if config.heartbeat and not config.disabled and can_authenticate:
tracker = OpenRootSpanTracker()
pipeline.add_span_processor(tracker)
if config.hints and heartbeat_transport is None:
inbox = HintInbox(
tracker.open_trace_ids,
per_trace=config.hints_per_trace,
on_hint=on_hint,
root_span=tracker.root_span,
)
sender = HeartbeatSender(
url=config.heartbeat_endpoint,
headers=config.headers,
interval=config.heartbeat_interval,
agent_name=config.agent_name,
instance_id=instance_id,
instance_secret=instance_secret,
tracker=tracker,
transport=heartbeat_transport,
foreign_parent_spans=None if detector is None else (lambda: detector.count),
hints=inbox,
)
sender.start()

Expand All @@ -890,12 +950,33 @@ def _do_init(
connectivity_thread=connectivity_thread,
routing=routing,
bridge=bridged,
hints=inbox,
)
if set_global:
_current_client = client
return client


def _why_hints_are_off(
config: GlassflowConfig,
heartbeat_transport: Callable[[dict[str, Any]], None] | None,
can_authenticate: bool,
) -> str | None:
"""Why hints cannot run with this configuration, or None when they can."""
if config.disabled:
return "rius is disabled (the kill switch is on)"
if not config.heartbeat:
return "the heartbeat is off, and hints ride on its response"
if heartbeat_transport is not None:
return (
"a custom heartbeat_transport is handed the payload only, so it cannot "
"authenticate the instance, and hints are delivered only to authenticated pings"
)
if not can_authenticate:
return "no credentials (set api_key or an Authorization header), so no heartbeat runs"
return None


def _foreign_global_name() -> str | None:
"""``module.Class`` of the global provider when another SDK already set it."""
existing = trace.get_tracer_provider()
Expand Down Expand Up @@ -952,6 +1033,19 @@ def _register_global(
return None


def drain_hints(trace_id: str | None = None) -> list[Hint]:
"""Remove and return the global client's hints for a run, oldest first.

See :meth:`GlassflowClient.drain_hints`. Empty when no global ``init()`` is
active or hints are off.
"""
with _lock:
client = _current_client
if client is None or client._is_shutdown:
return []
return client.drain_hints(trace_id)


def get_tracer(name: str = TRACER_NAME) -> trace.Tracer:
"""Return a tracer bound to the active global client's provider.

Expand Down
Loading
Loading