tracebin / client /tracebin.py
lvwerra's picture
lvwerra HF Staff
tracebin: capability-URL pastebin for agent traces
d0eee72 verified
Raw History Blame Contribute Delete
1.88 kB
"""Tiny client for pushing traces to a tracebin Space.
from tracebin import share
url = share(messages, title="run 41")
print(url)
Configure with environment variables:
TRACEBIN_URL https://your-space.hf.space
TRACEBIN_TOKEN upload token, if the Space sets one
"""
from __future__ import annotations
import json
import os
import urllib.error
import urllib.request
from typing import Any
class TracebinError(RuntimeError):
pass
def share(
trace: Any,
title: str = "",
base_url: str | None = None,
token: str | None = None,
timeout: float = 30.0,
) -> str:
"""Upload ``trace`` and return its secret URL.
The returned URL is the only way to reach the trace — nothing lists it.
Treat it like a password: don't print it into shared logs.
"""
base_url = (base_url or os.environ.get("TRACEBIN_URL", "")).rstrip("/")
if not base_url:
raise TracebinError("set TRACEBIN_URL or pass base_url=")
token = token if token is not None else os.environ.get("TRACEBIN_TOKEN", "")
body = json.dumps({"title": title, "trace": trace}, default=str).encode("utf-8")
request = urllib.request.Request(
f"{base_url}/api/traces",
data=body,
method="POST",
headers={"content-type": "application/json"},
)
if token:
request.add_header("x-upload-token", token)
try:
with urllib.request.urlopen(request, timeout=timeout) as response:
return json.loads(response.read())["url"]
except urllib.error.HTTPError as exc:
raise TracebinError(f"{exc.code}: {exc.read().decode('utf-8', 'replace')}") from exc
if __name__ == "__main__":
import sys
data = sys.stdin.read()
try:
payload = json.loads(data)
except ValueError:
payload = data
print(share(payload, title=" ".join(sys.argv[1:])))