File size: 5,263 Bytes
f039f41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
from __future__ import annotations

import json
import time
import urllib.error
import urllib.request
from dataclasses import dataclass
from typing import Any


@dataclass
class OpenAIClient:
    base_url: str
    api_key: str | None = None
    timeout_s: float = 600.0

    def _request(self, payload: dict[str, Any]):
        headers = {"Content-Type": "application/json"}
        if self.api_key:
            headers["Authorization"] = f"Bearer {self.api_key}"
        return urllib.request.Request(
            self.base_url.rstrip("/") + "/chat/completions",
            data=json.dumps(payload).encode("utf-8"),
            headers=headers,
        )

    def complete(self, payload: dict[str, Any], *, stream: bool = False) -> dict[str, Any]:
        body = dict(payload)
        body["stream"] = bool(stream)
        request = self._request(body)
        started = time.perf_counter()
        try:
            with urllib.request.urlopen(request, timeout=self.timeout_s) as response:
                if stream:
                    value = self._read_stream(response, started)
                else:
                    value = json.loads(response.read().decode("utf-8"))
        except urllib.error.HTTPError as exc:
            detail = exc.read().decode("utf-8", errors="replace")[-4000:]
            raise RuntimeError(f"HTTP {exc.code}: {detail}") from exc
        wall_s = time.perf_counter() - started
        return self._normalize(value, wall_s=wall_s, ttft_s=value.pop("_ttft_s", None))

    @staticmethod
    def _read_stream(response: Any, started: float) -> dict[str, Any]:
        content: list[str] = []
        reasoning: list[str] = []
        usage: dict[str, Any] = {}
        stats: dict[str, Any] = {}
        finish_reason = None
        first_token_at = None
        model = None
        for raw_line in response:
            line = raw_line.decode("utf-8", errors="replace").strip()
            if not line.startswith("data:"):
                continue
            data = line[5:].strip()
            if data == "[DONE]":
                break
            chunk = json.loads(data)
            model = chunk.get("model") or model
            usage = chunk.get("usage") or usage
            stats = chunk.get("mtplx_stats") or stats
            choice = (chunk.get("choices") or [{}])[0]
            delta = choice.get("delta") or {}
            text = delta.get("content") or ""
            thought = delta.get("reasoning_content") or ""
            if first_token_at is None and (text or thought):
                first_token_at = time.perf_counter()
            content.append(text)
            reasoning.append(thought)
            finish_reason = choice.get("finish_reason") or finish_reason
        return {
            "model": model,
            "choices": [
                {
                    "finish_reason": finish_reason,
                    "message": {
                        "role": "assistant",
                        "content": "".join(content),
                        "reasoning_content": "".join(reasoning),
                    },
                }
            ],
            "usage": usage,
            "mtplx_stats": stats,
            "_ttft_s": None if first_token_at is None else first_token_at - started,
        }

    @staticmethod
    def _normalize(value: dict[str, Any], *, wall_s: float, ttft_s: float | None) -> dict[str, Any]:
        choice = (value.get("choices") or [{}])[0]
        message = choice.get("message") or {}
        usage = value.get("usage") or {}
        stats = value.get("mtplx_stats") or usage.get("mtplx_stats") or {}
        if ttft_s is None and isinstance(stats.get("ttft_s"), (int, float)):
            ttft_s = float(stats["ttft_s"])
        completion_tokens = usage.get("completion_tokens")
        prompt_tokens = usage.get("prompt_tokens")
        return {
            "model": value.get("model"),
            "content": message.get("content") or "",
            "reasoning_content": message.get("reasoning_content") or "",
            "tool_calls": message.get("tool_calls") or [],
            "finish_reason": choice.get("finish_reason"),
            "usage": usage,
            "mtplx_stats": stats,
            "wall_s": wall_s,
            "ttft_s": ttft_s,
            "prompt_tokens": prompt_tokens,
            "completion_tokens": completion_tokens,
            "end_to_end_tokens_per_second": (
                completion_tokens / wall_s
                if isinstance(completion_tokens, int) and wall_s > 0
                else None
            ),
            "prefill_tokens_per_second": (
                stats.get("prefill_tok_s")
                or (
                    stats.get("new_prefill_tokens") / stats.get("prefill_elapsed_s")
                    if isinstance(stats.get("new_prefill_tokens"), (int, float))
                    and isinstance(stats.get("prefill_elapsed_s"), (int, float))
                    and stats.get("prefill_elapsed_s")
                    else None
                )
            ),
            "decode_tokens_per_second": stats.get("decode_tok_s") or stats.get("tok_s"),
            "active_memory_bytes": stats.get("active_memory_bytes"),
            "cache_memory_bytes": stats.get("cache_memory_bytes"),
        }