38 lines
1.3 KiB
Python
38 lines
1.3 KiB
Python
import json
|
|||
|
|
from collections.abc import Iterable
|
||
|
|
from typing import Any
|
||
|
|
|
||
|
|
|
||
|
|
def recovery_events(
|
||
|
|
*,
|
||
|
|
run_id: str,
|
||
|
|
trace_id: str,
|
||
|
|
status: str,
|
||
|
|
error_code: str | None,
|
||
|
|
content: str | None,
|
||
|
|
tool_calls: dict[str, Any] | None,
|
||
|
|
replay: bool = True,
|
||
|
|
chunk_size: int = 256,
|
||
|
|
) -> list[tuple[str, dict[str, Any]]]:
|
||
|
|
events: list[tuple[str, dict[str, Any]]] = [("start", {"run_id": run_id, "trace_id": trace_id})]
|
||
|
|
if status == "succeeded":
|
||
|
|
if tool_calls:
|
||
|
|
events.append(("tools", {"tool_calls": tool_calls}))
|
||
|
|
if replay:
|
||
|
|
events.append(("replace", {"content": content or ""}))
|
||
|
|
else:
|
||
|
|
body = content or ""
|
||
|
|
size = max(1, chunk_size)
|
||
|
|
for offset in range(0, max(1, len(body)), size):
|
||
|
|
events.append(("delta", {"content": body[offset:offset + size]}))
|
||
|
|
events.append(("done", {"status": status}))
|
||
|
|
elif status in {"failed", "cancelled"}:
|
||
|
|
events.append(("error", {"status": status, "error_code": error_code}))
|
||
|
|
return events
|
||
|
|
|
||
|
|
|
||
|
|
def encode_events(run_id: str, events: Iterable[tuple[str, dict[str, Any]]]) -> Iterable[str]:
|
||
|
|
for index, (event_name, payload) in enumerate(events):
|
||
|
|
data = json.dumps(payload, ensure_ascii=False)
|
||
|
|
yield f"event: {event_name}\ndata: {data}\nid: {run_id}:{event_name}:{index}\n\n"
|