harness-proxy 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- harness_proxy/__init__.py +0 -0
- harness_proxy/backends/__init__.py +19 -0
- harness_proxy/backends/tinker.py +71 -0
- harness_proxy/backends/together.py +150 -0
- harness_proxy/bridge.py +233 -0
- harness_proxy/chat.py +176 -0
- harness_proxy/client.py +305 -0
- harness_proxy/cookbook.py +163 -0
- harness_proxy/dialects/__init__.py +0 -0
- harness_proxy/dialects/anthropic.py +257 -0
- harness_proxy/dialects/openai.py +287 -0
- harness_proxy/keepalive.py +160 -0
- harness_proxy/py.typed +0 -0
- harness_proxy/rendering.py +205 -0
- harness_proxy/serve.py +292 -0
- harness_proxy/server.py +606 -0
- harness_proxy/trial.py +316 -0
- harness_proxy/tunnel.py +158 -0
- harness_proxy/vision.py +254 -0
- harness_proxy/wire.py +561 -0
- harness_proxy-0.1.0.dist-info/METADATA +108 -0
- harness_proxy-0.1.0.dist-info/RECORD +25 -0
- harness_proxy-0.1.0.dist-info/WHEEL +4 -0
- harness_proxy-0.1.0.dist-info/entry_points.txt +2 -0
- harness_proxy-0.1.0.dist-info/licenses/LICENSE +202 -0
|
File without changes
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from types import ModuleType
|
|
4
|
+
|
|
5
|
+
from harness_proxy.backends import tinker, together
|
|
6
|
+
|
|
7
|
+
#: Every backend, by the name a run gives it: a module with `PREFIX`, `connect`, `sampler`,
|
|
8
|
+
#: `context_of` and `close`.
|
|
9
|
+
BACKENDS: dict[str, ModuleType] = {"tinker": tinker, "together": together}
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def named(name: str) -> ModuleType:
|
|
13
|
+
"""Return the backend called `name`. Raise ValueError for an unknown one."""
|
|
14
|
+
try:
|
|
15
|
+
return BACKENDS[name]
|
|
16
|
+
except KeyError:
|
|
17
|
+
raise ValueError(
|
|
18
|
+
f"no backend {name!r}: the proxy samples from {', '.join(sorted(BACKENDS))}"
|
|
19
|
+
) from None
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
import os
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
logger = logging.getLogger(__name__)
|
|
8
|
+
|
|
9
|
+
PREFIX = "tinker://"
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
async def connect(
|
|
13
|
+
*,
|
|
14
|
+
metadata: dict[str, str] | None,
|
|
15
|
+
session: str | None,
|
|
16
|
+
base_url: str | None = None,
|
|
17
|
+
api_key_env: str | None = None,
|
|
18
|
+
) -> Any:
|
|
19
|
+
"""Return Tinker's service client, its session tagged with `metadata`: on the server at
|
|
20
|
+
`base_url`, with the key the variable `api_key_env` holds, or on the one the environment
|
|
21
|
+
names. `ValueError` if that variable is not set."""
|
|
22
|
+
import tinker
|
|
23
|
+
|
|
24
|
+
return tinker.ServiceClient(user_metadata=metadata, **reaching(base_url, api_key_env))
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def reaching(base_url: str | None, api_key_env: str | None) -> dict[str, str]:
|
|
28
|
+
"""Return what `tinker.ServiceClient` takes to reach the server at `base_url` with the key
|
|
29
|
+
the variable `api_key_env` holds; nothing for a None, which leaves it to the environment
|
|
30
|
+
(TINKER_BASE_URL, TINKER_API_KEY). `ValueError` if the variable is not set: the SDK would
|
|
31
|
+
send that server TINKER_API_KEY, Tinker's own key."""
|
|
32
|
+
found: dict[str, str] = {}
|
|
33
|
+
if base_url:
|
|
34
|
+
found["base_url"] = base_url
|
|
35
|
+
if api_key_env:
|
|
36
|
+
key = os.environ.get(api_key_env)
|
|
37
|
+
if not key:
|
|
38
|
+
raise ValueError(
|
|
39
|
+
f"{api_key_env} is not set: it holds the key of the Tinker server "
|
|
40
|
+
f"{base_url or 'the run reaches'}"
|
|
41
|
+
)
|
|
42
|
+
found["api_key"] = key
|
|
43
|
+
return found
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
async def sampler(service: Any, base_model: str, weights: str | None) -> Any:
|
|
47
|
+
"""Return a sampling client on the `tinker://` weights, or on the base model for None."""
|
|
48
|
+
if weights is None:
|
|
49
|
+
return await service.create_sampling_client_async(base_model=base_model)
|
|
50
|
+
return await service.create_sampling_client_async(model_path=weights)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
async def context_of(service: Any, base_model: str) -> int | None:
|
|
54
|
+
"""Return the model's context length from `get_server_capabilities`; None on any error."""
|
|
55
|
+
try:
|
|
56
|
+
caps = await service.get_server_capabilities_async()
|
|
57
|
+
for model in getattr(caps, "supported_models", None) or []:
|
|
58
|
+
if getattr(model, "model_name", None) == base_model:
|
|
59
|
+
return int(getattr(model, "max_context_length", 0) or 0) or None
|
|
60
|
+
except Exception: # noqa: BLE001 - the lane refuses, one way for any cause
|
|
61
|
+
logger.warning(
|
|
62
|
+
"could not read the context length of %s",
|
|
63
|
+
base_model,
|
|
64
|
+
exc_info=True,
|
|
65
|
+
)
|
|
66
|
+
return None
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
async def close(service: Any) -> None:
|
|
70
|
+
"""Finish the proxy's Tinker session as a success: the proxy's own shutdown was clean."""
|
|
71
|
+
await service.close("success")
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
from collections.abc import Sequence
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from functools import cache
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
|
|
11
|
+
from harness_proxy.chat import Refused
|
|
12
|
+
|
|
13
|
+
logger = logging.getLogger(__name__)
|
|
14
|
+
|
|
15
|
+
PREFIX = "together://"
|
|
16
|
+
#: Together's stop reasons, as Tinker names them.
|
|
17
|
+
STOPS = {"STOP_REASON_STOP": "stop", "STOP_REASON_LENGTH": "length"}
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
async def connect(*, metadata: dict[str, str] | None, session: str | None) -> Any:
|
|
21
|
+
"""Attach to the run's training session, whose generator the proxy samples."""
|
|
22
|
+
if not session:
|
|
23
|
+
raise ValueError(
|
|
24
|
+
"the together backend samples from the run's own session: pass its id as `session`"
|
|
25
|
+
)
|
|
26
|
+
from together.post_training import SessionClient
|
|
27
|
+
|
|
28
|
+
return await SessionClient.attach_async(session_id=session)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
async def sampler(service: Any, base_model: str, weights: str | None) -> Sampler:
|
|
32
|
+
"""Return a client on the session's generator, which serves the weights published last."""
|
|
33
|
+
return Sampler(service.generator)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
async def context_of(service: Any, base_model: str) -> int | None:
|
|
37
|
+
"""Return the model's context length from Together's supported models; None on any error."""
|
|
38
|
+
try:
|
|
39
|
+
from together import AsyncTogether
|
|
40
|
+
|
|
41
|
+
listed = await AsyncTogether().post_training.supported_models.get()
|
|
42
|
+
for model in listed.data:
|
|
43
|
+
if model.base_model == base_model:
|
|
44
|
+
configs = [one.generator_config for one in model.compute_configs or ()]
|
|
45
|
+
lengths = [one.context_length for one in configs if one is not None]
|
|
46
|
+
return max(lengths, default=None)
|
|
47
|
+
except Exception: # noqa: BLE001 - the lane refuses, one way for any cause
|
|
48
|
+
logger.warning(
|
|
49
|
+
"could not read the context length of %s",
|
|
50
|
+
base_model,
|
|
51
|
+
exc_info=True,
|
|
52
|
+
)
|
|
53
|
+
return None
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
async def close(service: Any) -> None:
|
|
57
|
+
"""Let the session go and leave it running: the run that opened it stops it."""
|
|
58
|
+
await service.detach_async()
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@dataclass
|
|
62
|
+
class Sampler:
|
|
63
|
+
"""A sampling client on a Together generator, answering as Tinker's does."""
|
|
64
|
+
|
|
65
|
+
generator: Any
|
|
66
|
+
|
|
67
|
+
async def sample_async(self, prompt: Any, num_samples: int, sampling_params: Any) -> Any:
|
|
68
|
+
try:
|
|
69
|
+
given = wire_input(prompt)
|
|
70
|
+
except ValueError as text_only:
|
|
71
|
+
raise Refused(str(text_only)) from None
|
|
72
|
+
result = await self.generator.sample_async(given, num_samples, wire_params(sampling_params))
|
|
73
|
+
found = response(result)
|
|
74
|
+
return Answer(found.sequences, found.prompt_cache_hit_tokens, versions_of(result))
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
@dataclass(frozen=True)
|
|
78
|
+
class Answer:
|
|
79
|
+
"""A Together sample as a trial reads it: Tinker's sequences and cached prompt tokens, and
|
|
80
|
+
the policy versions that wrote it, in order; the lane names the weights from them."""
|
|
81
|
+
|
|
82
|
+
sequences: list[Any]
|
|
83
|
+
prompt_cache_hit_tokens: int
|
|
84
|
+
versions: tuple[int, ...] = ()
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def versions_of(result: Any) -> tuple[int, ...]:
|
|
88
|
+
"""Return the policy versions a Together `SampleResult` says wrote it, in order: one for a
|
|
89
|
+
call the generator answered with one set of weights, as it always does a LoRA session's."""
|
|
90
|
+
return tuple(int(one.version) for one in getattr(result, "policy_segments", None) or ())
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def wire_input(model_input: Any) -> dict[str, Any]:
|
|
94
|
+
"""Return a Tinker `ModelInput` as Together's; ValueError for an image: it takes text only."""
|
|
95
|
+
chunks = []
|
|
96
|
+
for chunk in model_input.chunks:
|
|
97
|
+
if getattr(chunk, "type", "encoded_text") != "encoded_text":
|
|
98
|
+
raise ValueError("Together takes text only, and this input holds an image")
|
|
99
|
+
chunks.append({"encoded_text": {"tokens": [int(token) for token in chunk.tokens]}})
|
|
100
|
+
return {"chunks": chunks}
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def wire_params(params: Any) -> dict[str, Any]:
|
|
104
|
+
"""Return Tinker `SamplingParams` as Together's, dropping token-id stops with a warning."""
|
|
105
|
+
found: dict[str, Any] = {
|
|
106
|
+
"temperature": params.temperature,
|
|
107
|
+
"top_k": params.top_k,
|
|
108
|
+
"top_p": params.top_p,
|
|
109
|
+
}
|
|
110
|
+
if params.max_tokens is not None:
|
|
111
|
+
found["max_tokens"] = params.max_tokens
|
|
112
|
+
if params.seed is not None:
|
|
113
|
+
found["seed"] = params.seed
|
|
114
|
+
stops = [params.stop] if isinstance(params.stop, str) else list(params.stop or ())
|
|
115
|
+
strings = [one for one in stops if isinstance(one, str)]
|
|
116
|
+
if dropped := tuple(int(one) for one in stops if not isinstance(one, str)):
|
|
117
|
+
_dropped(dropped)
|
|
118
|
+
if strings:
|
|
119
|
+
found["stop"] = strings
|
|
120
|
+
return found
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def response(result: Any) -> Any:
|
|
124
|
+
"""Return a Together `SampleResult` as Tinker's `SampleResponse`."""
|
|
125
|
+
import tinker
|
|
126
|
+
|
|
127
|
+
sequences = [
|
|
128
|
+
tinker.types.SampledSequence(
|
|
129
|
+
stop_reason=STOPS.get(str(one.stop_reason), "stop"),
|
|
130
|
+
sequence_id=str(at),
|
|
131
|
+
tokens_np=np.asarray([int(token) for token in one.tokens], dtype=np.int32),
|
|
132
|
+
logprobs_np=_floats(one.logprobs),
|
|
133
|
+
)
|
|
134
|
+
for at, one in enumerate(result.sequences)
|
|
135
|
+
]
|
|
136
|
+
cached = int(result.sequences[0].prompt_cache_hit_tokens or 0) if result.sequences else 0
|
|
137
|
+
return tinker.types.SampleResponse(sequences=sequences, prompt_cache_hit_tokens=cached)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _floats(values: Sequence[float] | None) -> np.ndarray | None:
|
|
141
|
+
return None if values is None else np.asarray(values, dtype=np.float32)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
@cache
|
|
145
|
+
def _dropped(stops: tuple[int, ...]) -> None:
|
|
146
|
+
logger.warning(
|
|
147
|
+
"Together stops on strings only, so the token-id stops %s are left to the model's "
|
|
148
|
+
"end-of-sequence token",
|
|
149
|
+
list(stops),
|
|
150
|
+
)
|
harness_proxy/bridge.py
ADDED
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
import json
|
|
5
|
+
from array import array
|
|
6
|
+
from collections.abc import Sequence
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from harness_proxy.vision import image_key
|
|
11
|
+
from harness_proxy.wire import Picture, ids_of, pictures_of
|
|
12
|
+
|
|
13
|
+
# ----------------------------------------------------------------------- the digest
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _field(value: Any, name: str) -> Any:
|
|
17
|
+
if isinstance(value, dict):
|
|
18
|
+
return value.get(name)
|
|
19
|
+
return getattr(value, name, None) if value is not None else None
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _call(call: Any) -> list[str]:
|
|
23
|
+
"""Return a tool call's name and id, without its arguments, which a harness may rewrite."""
|
|
24
|
+
function = _field(call, "function")
|
|
25
|
+
named = function if function is not None else call
|
|
26
|
+
return [str(_field(named, "name") or ""), str(_field(call, "id") or "")]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def normalize(message: Any) -> dict[str, Any]:
|
|
30
|
+
"""Return the fields that identify a message, for digesting."""
|
|
31
|
+
content = _field(message, "content")
|
|
32
|
+
text: list[str] = []
|
|
33
|
+
thinking: list[str] = []
|
|
34
|
+
images: list[str] = []
|
|
35
|
+
if isinstance(content, str):
|
|
36
|
+
text.append(content)
|
|
37
|
+
elif isinstance(content, list):
|
|
38
|
+
for part in content:
|
|
39
|
+
if not isinstance(part, dict):
|
|
40
|
+
continue
|
|
41
|
+
if part.get("type") == "text":
|
|
42
|
+
text.append(str(part.get("text") or ""))
|
|
43
|
+
elif part.get("type") == "thinking":
|
|
44
|
+
thinking.append(str(part.get("thinking") or ""))
|
|
45
|
+
elif part.get("type") == "image":
|
|
46
|
+
images.append(image_key(part))
|
|
47
|
+
return {
|
|
48
|
+
"role": str(_field(message, "role") or ""),
|
|
49
|
+
"text": "".join("".join(text).split()),
|
|
50
|
+
"thinking": "".join(thinking),
|
|
51
|
+
"images": images,
|
|
52
|
+
"calls": [_call(call) for call in (_field(message, "tool_calls") or [])],
|
|
53
|
+
"name": str(_field(message, "name") or ""),
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def canon(value: Any) -> str:
|
|
58
|
+
return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False, default=str)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def digest(message: Any) -> str:
|
|
62
|
+
return hashlib.sha256(canon(normalize(message)).encode("utf-8")).hexdigest()[:16]
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def render_digest(ids: Sequence[int]) -> str:
|
|
66
|
+
"""Return a digest of a rendered prompt's token ids, which two renders share only if they
|
|
67
|
+
are the same tokens: what a reply keeps of the render its prompt would have had."""
|
|
68
|
+
return hashlib.blake2b(array("q", ids).tobytes(), digest_size=16).hexdigest()
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def digests_of(messages: Sequence[Any]) -> tuple[str, ...]:
|
|
72
|
+
return tuple(digest(message) for message in messages)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def chains(digests: Sequence[str]) -> list[str]:
|
|
76
|
+
"""Return a key for every prefix of `digests`, each derived from the one before."""
|
|
77
|
+
out: list[str] = []
|
|
78
|
+
last = ""
|
|
79
|
+
for one in digests:
|
|
80
|
+
last = hashlib.sha256(f"{last}/{one}".encode()).hexdigest()[:16]
|
|
81
|
+
out.append(last)
|
|
82
|
+
return out
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def chain(digests: Sequence[str]) -> str:
|
|
86
|
+
return chains(digests)[-1] if digests else ""
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
# ------------------------------------------------------------------------ the index
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
@dataclass(frozen=True)
|
|
93
|
+
class Reply:
|
|
94
|
+
"""A sampled reply, stored for the bridge: its prompt, completion, stop and pictures, and the
|
|
95
|
+
digest of the fresh render of its prompt's messages."""
|
|
96
|
+
|
|
97
|
+
prompt_ids: Sequence[int]
|
|
98
|
+
completion_ids: tuple[int, ...]
|
|
99
|
+
ended_with_stop: bool
|
|
100
|
+
#: `render_digest` of the fresh render, which a later prompt's head must have to extend this
|
|
101
|
+
#: reply. The render itself is as long as the prompt, so a trial keeps none of them.
|
|
102
|
+
rendered: str
|
|
103
|
+
pictures: tuple[Picture, ...] = ()
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
class Index:
|
|
107
|
+
"""The sampled replies of one trial, each keyed by the digest chain that leads to it."""
|
|
108
|
+
|
|
109
|
+
def __init__(self) -> None:
|
|
110
|
+
self._replies: dict[str, Reply] = {}
|
|
111
|
+
self._ambiguous: set[str] = set()
|
|
112
|
+
#: Replies by (history, identity), where the identity is a call id or, for a reply
|
|
113
|
+
#: that makes no call, its digest.
|
|
114
|
+
self._carried: dict[tuple[str, str], list[tuple[str, Reply]]] = {}
|
|
115
|
+
|
|
116
|
+
def __len__(self) -> int:
|
|
117
|
+
return len(self._replies)
|
|
118
|
+
|
|
119
|
+
def add(
|
|
120
|
+
self,
|
|
121
|
+
prompt_digests: Sequence[str],
|
|
122
|
+
reply_digest: str,
|
|
123
|
+
reply: Reply,
|
|
124
|
+
call_ids: Sequence[str] = (),
|
|
125
|
+
) -> None:
|
|
126
|
+
key, history = chain([*prompt_digests, reply_digest]), chain(prompt_digests)
|
|
127
|
+
identities = [f"call:{one}" for one in call_ids] or [f"reply:{reply_digest}"]
|
|
128
|
+
for identity in identities:
|
|
129
|
+
carried = self._carried.setdefault((history, identity), [])
|
|
130
|
+
for other_key, other in carried:
|
|
131
|
+
if other.completion_ids != reply.completion_ids:
|
|
132
|
+
self._ambiguous.update((key, other_key))
|
|
133
|
+
carried.append((key, reply))
|
|
134
|
+
self._replies[key] = reply
|
|
135
|
+
|
|
136
|
+
def find(self, digests: Sequence[str]) -> tuple[int, Reply] | None:
|
|
137
|
+
"""Find the longest prefix of `digests` that ends in a sampled reply, or None."""
|
|
138
|
+
keys = chains(digests)
|
|
139
|
+
for end in range(len(keys), 0, -1):
|
|
140
|
+
if keys[end - 1] in self._ambiguous:
|
|
141
|
+
return None
|
|
142
|
+
reply = self._replies.get(keys[end - 1])
|
|
143
|
+
if reply is not None:
|
|
144
|
+
return end - 1, reply
|
|
145
|
+
return None
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
# ----------------------------------------------------------------------- the bridge
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
@dataclass(frozen=True)
|
|
152
|
+
class Bridged:
|
|
153
|
+
ids: tuple[int, ...]
|
|
154
|
+
#: `render_digest` of the fresh render of the messages, which the head of a later prompt
|
|
155
|
+
#: must have to extend this one.
|
|
156
|
+
rendered: str
|
|
157
|
+
#: Pictures behind the image tokens in `ids`: the reply's first, then the tail's.
|
|
158
|
+
pictures: tuple[Picture, ...] = ()
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def bridge(
|
|
162
|
+
messages: Sequence[Any],
|
|
163
|
+
renderer: Any,
|
|
164
|
+
index: Index,
|
|
165
|
+
digests: Sequence[str] | None = None,
|
|
166
|
+
) -> Bridged | None:
|
|
167
|
+
"""Build the prompt for `messages` from the tokens of a sampled reply they quote, or None."""
|
|
168
|
+
digests = digests_of(messages) if digests is None else digests
|
|
169
|
+
found = index.find(digests)
|
|
170
|
+
if found is None:
|
|
171
|
+
return None
|
|
172
|
+
at, reply = found
|
|
173
|
+
if at < 1 or not tail_extends(messages[at + 1 :]):
|
|
174
|
+
return None
|
|
175
|
+
stops = int_stops(renderer)
|
|
176
|
+
if not stops:
|
|
177
|
+
return None
|
|
178
|
+
head = ids_of(renderer.build_generation_prompt(list(messages[:at])))
|
|
179
|
+
if render_digest(head) != reply.rendered:
|
|
180
|
+
return None
|
|
181
|
+
fresh = renderer.build_generation_prompt(list(messages))
|
|
182
|
+
full = ids_of(fresh)
|
|
183
|
+
if full[: len(head)] != head:
|
|
184
|
+
return None
|
|
185
|
+
end = next((i for i in range(len(head), len(full)) if full[i] in stops), None)
|
|
186
|
+
if end is None or not _ends_reply(full, end, messages, at, renderer, stops):
|
|
187
|
+
return None
|
|
188
|
+
closing = () if reply.ended_with_stop else (full[end],)
|
|
189
|
+
spliced = (*reply.prompt_ids, *reply.completion_ids, *closing, *full[end + 1 :])
|
|
190
|
+
# An image in the head is the reply's picture; one in the tail moves with the tail.
|
|
191
|
+
shift = len(spliced) - len(full)
|
|
192
|
+
tail = tuple(
|
|
193
|
+
Picture(one.offset + shift, one.length, one.format, one.data)
|
|
194
|
+
for one in pictures_of(fresh)
|
|
195
|
+
if one.offset > end
|
|
196
|
+
)
|
|
197
|
+
return Bridged(spliced, render_digest(full), (*reply.pictures, *tail))
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def _ends_reply(
|
|
201
|
+
full: Sequence[int], end: int, messages: Sequence[Any], at: int, renderer: Any, stops: set[int]
|
|
202
|
+
) -> bool:
|
|
203
|
+
"""Return whether the stop at `end` of the fresh render closes the reply at `at`."""
|
|
204
|
+
calls = [_bare(call) for call in _field(messages[at], "tool_calls") or []]
|
|
205
|
+
stub: dict[str, Any] = {"role": "assistant", "content": "."}
|
|
206
|
+
if calls:
|
|
207
|
+
stub["tool_calls"] = calls
|
|
208
|
+
held = renderer.build_generation_prompt([*messages[:at], stub, *messages[at + 1 :]])
|
|
209
|
+
alt, tail = ids_of(held), tuple(full[end + 1 :])
|
|
210
|
+
cut = len(alt) - len(tail)
|
|
211
|
+
return cut >= 1 and alt[cut:] == tail and alt[cut - 1] in stops
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _bare(call: Any) -> Any:
|
|
215
|
+
"""Return the tool call with `{}` for arguments, which hold text the model wrote."""
|
|
216
|
+
function = _field(call, "function")
|
|
217
|
+
if isinstance(call, dict):
|
|
218
|
+
return {**call, "function": {**(function or {}), "arguments": "{}"}}
|
|
219
|
+
return call.model_copy(update={"function": function.model_copy(update={"arguments": "{}"})})
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def tail_extends(tail: Sequence[Any]) -> bool:
|
|
223
|
+
"""Return whether the messages after a quoted reply can be bridged (prime-rl's tail rule)."""
|
|
224
|
+
roles = [str(_field(message, "role") or "") for message in tail]
|
|
225
|
+
if not roles:
|
|
226
|
+
return False
|
|
227
|
+
body = roles[:-1] if roles[-1] == "user" else roles
|
|
228
|
+
return all(role == "tool" for role in body)
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def int_stops(renderer: Any) -> set[int]:
|
|
232
|
+
"""Return the renderer's stop sequences that are token ids, skipping string stops."""
|
|
233
|
+
return {int(s) for s in (renderer.get_stop_sequences() or []) if isinstance(s, int)}
|
harness_proxy/chat.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import uuid
|
|
4
|
+
from collections.abc import Sequence
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from harness_proxy.cookbook import Message, ToolCall, ToolSpec
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class Refused(Exception):
|
|
12
|
+
"""A request the proxy will not serve, answered with a 400 in the wire's own shape."""
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True)
|
|
16
|
+
class Caller:
|
|
17
|
+
"""Who made a call: the trial its token opened, the wire it came on, and the SDK's retry
|
|
18
|
+
headers."""
|
|
19
|
+
|
|
20
|
+
trial: str = ""
|
|
21
|
+
#: `anthropic` for a call on `/messages`, otherwise `openai`. Determines the form of the
|
|
22
|
+
#: tool call ids the proxy mints.
|
|
23
|
+
wire: str = "openai"
|
|
24
|
+
retry: int = 0
|
|
25
|
+
idempotency_key: str | None = None
|
|
26
|
+
request_id: str | None = None
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass
|
|
30
|
+
class Call:
|
|
31
|
+
"""A request as its dialect reads it: the conversation, and what the harness asked for."""
|
|
32
|
+
|
|
33
|
+
messages: list[Message]
|
|
34
|
+
system: str | None = None
|
|
35
|
+
tools: list[ToolSpec] = field(default_factory=list)
|
|
36
|
+
#: `tool_choice` "none": the prompt gets no tools and the reply's calls are dropped, because
|
|
37
|
+
#: a model can write its learned call syntax without a catalog.
|
|
38
|
+
no_tools: bool = False
|
|
39
|
+
model: str | None = None
|
|
40
|
+
#: None for the server's default.
|
|
41
|
+
max_tokens: int | None = None
|
|
42
|
+
temperature: float | None = None
|
|
43
|
+
top_p: float | None = None
|
|
44
|
+
top_k: int | None = None
|
|
45
|
+
seed: int | None = None
|
|
46
|
+
#: The harness's own stop strings.
|
|
47
|
+
stop: list[str] | None = None
|
|
48
|
+
stream: bool = False
|
|
49
|
+
#: OpenAI's `stream_options.include_usage`.
|
|
50
|
+
include_usage: bool = False
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@dataclass
|
|
54
|
+
class Reply:
|
|
55
|
+
"""A sampled reply, parsed, before a dialect writes it."""
|
|
56
|
+
|
|
57
|
+
text: str
|
|
58
|
+
thinking: str
|
|
59
|
+
tool_calls: list[ToolCall]
|
|
60
|
+
prompt_tokens: int
|
|
61
|
+
completion_tokens: int
|
|
62
|
+
#: Tinker's stop reason: "stop" or "length".
|
|
63
|
+
stop_reason: str
|
|
64
|
+
#: Whether sampling ended on one of the call's own stop strings, and which one if known.
|
|
65
|
+
client_stop: bool = False
|
|
66
|
+
matched_stop: str | None = None
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def thinking_of(message: Any) -> str:
|
|
70
|
+
"""Return the joined thinking parts of a parsed message, or `""` if it has none."""
|
|
71
|
+
content = message.get("content") if isinstance(message, dict) else None
|
|
72
|
+
parts = content if isinstance(content, list) else []
|
|
73
|
+
return "".join(
|
|
74
|
+
str(p.get("thinking") or "")
|
|
75
|
+
for p in parts
|
|
76
|
+
if isinstance(p, dict) and p.get("type") == "thinking"
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
# ------------------------------------------------------------------- reading a request
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def text_part(text: Any) -> dict[str, str]:
|
|
84
|
+
return {"type": "text", "text": str(text)}
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def content_of(parts: Sequence[dict[str, Any]]) -> str | list[dict[str, Any]]:
|
|
88
|
+
"""Return a message's content from its parts, in order: text alone as one string."""
|
|
89
|
+
if all(part.get("type") == "text" for part in parts):
|
|
90
|
+
return "".join(str(part.get("text") or "") for part in parts)
|
|
91
|
+
merged: list[dict[str, Any]] = []
|
|
92
|
+
for part in parts:
|
|
93
|
+
if part.get("type") == "text":
|
|
94
|
+
if not part.get("text"):
|
|
95
|
+
continue
|
|
96
|
+
if merged and merged[-1].get("type") == "text":
|
|
97
|
+
merged[-1] = text_part(merged[-1]["text"] + str(part["text"]))
|
|
98
|
+
continue
|
|
99
|
+
merged.append(part)
|
|
100
|
+
return merged
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def reject(body: dict[str, Any], keys: Sequence[str]) -> None:
|
|
104
|
+
"""Refuse a request that sets a field the proxy would silently ignore."""
|
|
105
|
+
for key in keys:
|
|
106
|
+
if body.get(key):
|
|
107
|
+
raise Refused(f"{key!r} is not supported by this proxy")
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def positive_int(value: Any, key: str) -> int | None:
|
|
111
|
+
if value is None:
|
|
112
|
+
return None
|
|
113
|
+
if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
|
|
114
|
+
raise Refused(f"{key!r} must be a positive integer")
|
|
115
|
+
return value
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def integer(value: Any, key: str) -> int | None:
|
|
119
|
+
if value is None:
|
|
120
|
+
return None
|
|
121
|
+
if isinstance(value, bool) or not isinstance(value, int):
|
|
122
|
+
raise Refused(f"{key!r} must be an integer")
|
|
123
|
+
return value
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def number(value: Any, key: str) -> float | None:
|
|
127
|
+
if value is None:
|
|
128
|
+
return None
|
|
129
|
+
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
|
130
|
+
raise Refused(f"{key!r} must be a number")
|
|
131
|
+
return float(value)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def stop_strings(value: Any, key: str) -> list[str] | None:
|
|
135
|
+
if value is None:
|
|
136
|
+
return None
|
|
137
|
+
if isinstance(value, str):
|
|
138
|
+
return [value]
|
|
139
|
+
if isinstance(value, list) and all(isinstance(item, str) for item in value):
|
|
140
|
+
return value
|
|
141
|
+
raise Refused(f"{key!r} must be a string or a list of strings")
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def check_tool_choice(value: Any) -> None:
|
|
145
|
+
"""Accept no choice, auto or none. A forced choice has no renderer mechanism."""
|
|
146
|
+
if value is None or value in ("auto", "none"):
|
|
147
|
+
return
|
|
148
|
+
if isinstance(value, dict) and value.get("type") in ("auto", "none"):
|
|
149
|
+
return
|
|
150
|
+
raise Refused("forced 'tool_choice' is not supported by this proxy; omit it or use auto/none")
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def forbids_tools(value: Any) -> bool:
|
|
154
|
+
"""Return whether the tool choice is OpenAI's `"none"` or Anthropic's `{"type": "none"}`."""
|
|
155
|
+
return value == "none" or (isinstance(value, dict) and value.get("type") == "none")
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def tool_spec(name: Any, description: Any, parameters: Any) -> ToolSpec:
|
|
159
|
+
if not isinstance(name, str) or not name:
|
|
160
|
+
raise Refused("each tool requires a non-empty string 'name'")
|
|
161
|
+
if parameters is not None and not isinstance(parameters, dict):
|
|
162
|
+
raise Refused(f"tool {name!r} parameter schema must be an object")
|
|
163
|
+
return ToolSpec(
|
|
164
|
+
name=name,
|
|
165
|
+
description=str(description or ""),
|
|
166
|
+
parameters=parameters or {"type": "object", "properties": {}},
|
|
167
|
+
)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def tool_call(call_id: Any, name: Any, arguments: str) -> ToolCall:
|
|
171
|
+
if not isinstance(name, str) or not name:
|
|
172
|
+
raise Refused("each tool call requires a non-empty string tool name")
|
|
173
|
+
return ToolCall(
|
|
174
|
+
id=str(call_id) if call_id else f"toolu_{uuid.uuid4().hex}",
|
|
175
|
+
function=ToolCall.FunctionBody(name=name, arguments=arguments),
|
|
176
|
+
)
|