Skip to content

Latest commit

 

History

History
411 lines (317 loc) · 13.5 KB

manual-tracking.md

File metadata and controls

411 lines (317 loc) · 13.5 KB

Manual tracking

Use manual tracking when your framework is not covered by a WildEdge integration, or when you need richer metadata than auto-instrumentation provides.

When to use it

  • Your model class is custom (e.g. a torch.nn.Module subclass not loaded via timm or transformers)
  • You are calling a remote API not yet covered by an integration (for LLM APIs called over raw HTTP, wildedge.llm_api() is the shortcut)
  • You want to attach input/output metadata (token counts, image dimensions, confidence scores, etc.)
  • You want to record user feedback tied to a specific inference

The default client

Every process has at most one default client, and the module-level API delegates to it. You rarely need to hold a client instance yourself:

import wildedge

with wildedge.trace(run_id="run-123"):
    with wildedge.span(kind="agent_step", name="plan", step_index=1):
        ...

The default client comes from wherever initialization happened first:

  • wildedge run installs one before your code loads. A later wildedge.init() without dsn, or with the same DSN, reuses it, so the same code works with or without the CLI wrapper.
  • wildedge.init(...) creates one (or reuses the existing default) and registers it.
  • Any module-level call (wildedge.span, wildedge.register_model, ...) creates one lazily from the environment: WILDEDGE_DSN for the endpoint (without it the client is a no-op), plus WILDEDGE_INTEGRATIONS and WILDEDGE_HUBS for auto-instrumentation. Unset means nothing is patched.

wildedge.get_client() returns the default client when you need direct access; wildedge.set_default_client() overrides it (useful in tests). wildedge.trace is the exception to the delegation rule: a trace only sets correlation contextvars and emits nothing, so it never touches or creates a client.

Auto-instrumentation patches at creation time, so ordering matters: the CLI patches before any user code runs, an early init() covers everything created after it, and a lazily created client only covers what is created after the first module-level call. When in doubt, call init() at application startup.

torch and keras

For torch and keras, models are user-defined subclasses with no constructor to patch. Use client.load() to get load, unload, and inference tracking automatically:

model = client.load(MyModel)
output = model(x)  # tracked automatically

Register your model

Every model needs a handle before you can track events against it. Pass the model object and an explicit model_id:

import wildedge

client = wildedge.init()  # uses WILDEDGE_DSN if set; otherwise no-op

# Optional: enable auto-instrumentation alongside manual tracking.
# client = wildedge.init(integrations=["transformers"], hubs=["huggingface"])

handle = client.register_model(
    my_model,
    model_id="my-org/my-model",
    source="local",        # where the weights came from
    family="resnet",       # optional model family
    version="1.0.0",       # optional version string
    quantization="int8",   # optional quantization label
)

For remote APIs with no local object to inspect, pass a placeholder:

handle = client.register_model(
    None,
    model_id="openai/gpt-4o",
    source="openai",
    family="gpt-4o",
    version="2024-08-06",
    model_format="api",
)

register_model is idempotent - calling it twice with the same model_id returns the existing handle.

Track inference

Decorator

WildEdge times the function and records success or error automatically:

@wildedge.track(handle, input_type="text", output_type="text")
def generate(prompt: str) -> str:
    return my_model(prompt)

Context manager

Use this when you need access to the result before emitting the event, or when the tracked block is not a standalone function:

with wildedge.track(handle, input_type="image", output_type="structured"):
    result = my_model(image_tensor)

Direct call

For full control over metadata - token counts, confidence scores, generation config, etc.:

from wildedge import GenerationConfig, GenerationOutputMeta, TextInputMeta
from wildedge.timing import Timer

with Timer() as t:
    result = my_model(prompt)

inference_id = handle.track_inference(
    duration_ms=t.elapsed_ms,
    input_modality="text",
    output_modality="generation",
    success=True,
    input_meta=TextInputMeta(
        token_count=len(prompt.split()),
        prompt_type="chat",
    ),
    output_meta=GenerationOutputMeta(
        tokens_in=input_tokens,
        tokens_out=output_tokens,
        tokens_per_second=round(output_tokens / t.elapsed_ms * 1000, 1),
        stop_reason="stop",
    ),
    generation_config=GenerationConfig(
        temperature=0.7,
        max_tokens=512,
    ),
)

track_inference returns an inference_id string you can use to attach feedback later.

Input and output metadata

All fields are optional.

Text input (TextInputMeta)

Field Type Description
char_count int Character count
word_count int Word count
token_count int Token count
language str BCP-47 language code
prompt_type str e.g. "chat", "completion", "instruct"
turn_index int Position in a multi-turn conversation
contains_code bool Whether the input contains code

Image input (ImageInputMeta)

Field Type Description
width int Pixel width
height int Pixel height
channels int Channel count
format str e.g. "jpeg", "png", "rgb"
source str e.g. "camera", "file", "stream"

Audio input (AudioInputMeta)

Field Type Description
duration_ms int Audio length
sample_rate int Hz
channels int Channel count
format str e.g. "wav", "mp3"
is_streaming bool Live stream vs pre-recorded

Generation output (GenerationOutputMeta)

Field Type Description
tokens_in int Prompt token count
tokens_out int Completion token count
tokens_per_second float Generation throughput
cached_input_tokens int Tokens served from KV cache
reasoning_tokens_out int Reasoning/thinking tokens (e.g. o1)
time_to_first_token_ms int TTFT latency
stop_reason str e.g. "stop", "length", "content_filter"

Classification output (ClassificationOutputMeta)

Field Type Description
num_predictions int Number of predictions returned
avg_confidence float Mean confidence across predictions
top_k list[TopKPrediction] Top-k labels with confidence scores

Detection output (DetectionOutputMeta)

Field Type Description
num_predictions int Number of detections
avg_confidence float Mean confidence
top_k list[TopKPrediction] Top detections with bounding boxes

Embedding output (EmbeddingOutputMeta)

Field Type Description
dimensions int Embedding vector size

Track errors

try:
    result = my_model(input)
except Exception as exc:
    handle.track_error(
        error_code="UNKNOWN",
        error_message=str(exc),
    )
    raise

wildedge.track (decorator and context manager) captures errors automatically when capture_errors=True (the default).

For failed calls to a remote model API, pass http_status and, if the provider returned one, provider_error_code with error_code="UNKNOWN"; Wild Edge derives the error code from them. The openai and anthropic integrations do this automatically, and report timeouts and connection failures as INFERENCE_TIMEOUT and CONNECTION_ERROR.

Track feedback

Link user or automated feedback to a specific inference via the inference_id returned by track_inference:

from wildedge import FeedbackType

inference_id = handle.track_inference(duration_ms=..., ...)

# Later, when feedback is available
handle.track_feedback(inference_id, FeedbackType.THUMBS_UP)

If you always want to attach feedback to the most recent inference on a handle, use the shorthand:

handle.feedback(FeedbackType.THUMBS_DOWN)

FeedbackType values: THUMBS_UP, THUMBS_DOWN.

Track attachments

Opt-in upload of the raw bytes behind an inference, such as the source image, audio clip, or generated text, so you can inspect or curate them later. This is off by default and requires the attachment feature enabled on your project. Enable it at init, then pass attachments= to track_inference. Automatic integrations, including GGUF and Whisper, do not supply attachments. When tracking the inference manually, use auto_instrument=False at model registration to avoid recording the same call twice:

import wildedge
from wildedge import Attachment

client = wildedge.init(attachments_enabled=True)
handle = client.register_model(
    model, model_id="doc-classifier-v1", auto_instrument=False
)

handle.track_inference(
    duration_ms=120,
    input_modality="image",
    output_modality="text",
    attachments=[
        Attachment(content_type="image/jpeg", role="input", data=image_bytes),
        Attachment(content_type="text/plain", role="output", data=answer.encode()),
    ],
)

An Attachment carries either in-memory data or a file path, plus a role ("input" or "output") and content_type. The SDK writes a reference into the inference event immediately and uploads the bytes in the background via a presigned URL. A failed or disabled upload never blocks telemetry.

Bytes are buffered to disk and survive restarts. Capture is gated by max_attachments_per_inference, max_attachment_size_bytes, and an optional attachment_filter hook. See Configuration and examples/attachments_example.py for the full reference.

Explicit GGUF prompt and reply attachments

Use manual tracking when you want to attach GGUF payloads:

import wildedge
from llama_cpp import Llama
from wildedge import Attachment
from wildedge.timing import Timer

client = wildedge.init(integrations=[], attachments_enabled=True)
llm = Llama(model_path="/models/model.gguf")
handle = client.register_model(llm, auto_instrument=False)
prompt = "Explain how rain forms."
with Timer() as timer:
    result = llm.create_completion(prompt=prompt, max_tokens=128)
reply = result["choices"][0]["text"]
handle.track_inference(
    duration_ms=timer.elapsed_ms,
    input_modality="text",
    output_modality="generation",
    attachments=[
        Attachment(content_type="text/plain", role="input", data=prompt.encode()),
        Attachment(content_type="text/plain", role="output", data=reply.encode()),
    ],
)
client.close(timeout=10)

Track spans for agentic workflows

Use span events to track non-inference steps like planning, tool calls, retrieval, or memory updates.

from wildedge.timing import Timer

with Timer() as t:
    tool_result = call_tool()

client.track_span(
    kind="tool",
    name="call_tool",
    duration_ms=t.elapsed_ms,
    status="ok",
    attributes={"tool": "search"},
)

Span attribute values should be strings, numbers, booleans or None. Lists, dicts and other values are sent as JSON strings (["a", "b"] arrives as '["a", "b"]'), and the SDK logs a warning the first time it sees each such key.

You can also attach optional correlation fields (trace_id, span_id, parent_span_id, run_id, agent_id, step_index, conversation_id) to any event by passing them into track_inference, track_error, track_feedback, or track_span. Use context= for correlation attributes shared across events.

Trace context helpers

Use client.trace() and client.span() to auto-populate correlation fields for all events emitted inside the block. client.span() times the block and emits a span event on exit:

import wildedge
from wildedge.timing import Timer

client = wildedge.init()
handle = client.register_model(my_model, model_id="my-org/my-model")

with client.trace(run_id="run-123", agent_id="agent-1"):
    with client.span(kind="agent_step", name="plan", step_index=1):
        with Timer() as t:
            result = my_model(prompt)
        handle.track_inference(duration_ms=t.elapsed_ms, input_modality="text", output_modality="generation")

Both are also available module-level on the default client, so this is equivalent without holding a client:

with wildedge.trace(run_id="run-123", agent_id="agent-1"):
    with wildedge.span(kind="agent_step", name="plan", step_index=1):
        ...

Recording results on an open span

The span object is mutable until the block exits; set outcomes you only know mid-block directly on it. set_attributes() merges into the span's attributes, fail() marks it failed with an optional summary, and an exception escaping the block sets status="error" automatically:

with wildedge.span(kind="eval", name="lint") as span:
    errors = lint(result)
    span.set_attributes(lint_errors=len(errors))
    if errors:
        span.fail(f"{len(errors)} lint errors")

If you need to set correlation fields without emitting a span event, use the lower-level span_context() directly:

with client.trace(run_id="run-123", agent_id="agent-1"):
    with wildedge.span_context(step_index=1):
        with Timer() as t:
            result = my_model(prompt)
        handle.track_inference(duration_ms=t.elapsed_ms, input_modality="text", output_modality="generation")