tokin 0.0.1__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.
tokin/__init__.py ADDED
@@ -0,0 +1,8 @@
1
+ from importlib.metadata import version
2
+
3
+ from .chat_templates import ChatTemplate, ChatTemplateError, get_chat_template
4
+ from .rollout import Rollout, Turn
5
+ from .session import Session
6
+
7
+ __version__ = version("tokin")
8
+ __all__ = ["ChatTemplate", "ChatTemplateError", "Rollout", "Session", "Turn", "__version__", "get_chat_template"]
@@ -0,0 +1,28 @@
1
+ import importlib
2
+
3
+ from .chat_template import ChatTemplate, ChatTemplateError
4
+ from .glm import GLMChatTemplate
5
+ from .qwen import Qwen35ChatTemplate, QwenChatTemplate
6
+
7
+ CHAT_TEMPLATES: dict[str, type[ChatTemplate]] = {
8
+ t.name: t for t in (QwenChatTemplate, Qwen35ChatTemplate, GLMChatTemplate)
9
+ }
10
+
11
+
12
+ def get_chat_template(name: str) -> type[ChatTemplate]:
13
+ """The family called `name`, the one a checkpoint id in `models` belongs to, or a `module:Class` to import."""
14
+ if name in CHAT_TEMPLATES:
15
+ return CHAT_TEMPLATES[name]
16
+ for template in CHAT_TEMPLATES.values():
17
+ if name in template.models:
18
+ return template
19
+ if ":" in name:
20
+ module, _, attr = name.partition(":")
21
+ template = getattr(importlib.import_module(module), attr)
22
+ if isinstance(template, type) and issubclass(template, ChatTemplate):
23
+ return template
24
+ raise TypeError(f"{name} is not a ChatTemplate subclass")
25
+ raise ValueError(f"unknown chat template {name!r}; known: {list(CHAT_TEMPLATES)}")
26
+
27
+
28
+ __all__ = ["CHAT_TEMPLATES", "ChatTemplate", "ChatTemplateError", "get_chat_template"]
@@ -0,0 +1,211 @@
1
+ from __future__ import annotations
2
+
3
+ import copy
4
+ import itertools
5
+ import json
6
+ from collections.abc import Iterable
7
+ from typing import Any, ClassVar, cast
8
+
9
+ from transformers import PreTrainedTokenizerBase
10
+
11
+ from ..tool_parsers import ToolParser
12
+ from ..types import (
13
+ AssistantMessage,
14
+ Message,
15
+ PromptMessage,
16
+ SystemMessage,
17
+ ToolCall,
18
+ ToolSchema,
19
+ UserMessage,
20
+ )
21
+
22
+
23
+ class ChatTemplateError(RuntimeError):
24
+ """The template cannot continue a served prompt with these messages; start over from `apply`."""
25
+
26
+
27
+ class ChatTemplate:
28
+ """One model family's chat format, bound to a tokenizer.
29
+
30
+ A subclass states the family's facts as class attributes and inherits the
31
+ behaviour; a family without a jinja template overrides `apply` as well.
32
+
33
+ Attributes:
34
+ name (str): Registry key, such as `"qwen"`.
35
+ turn_end (str): What the template writes after assistant content, such as
36
+ `"<|im_end|>\n"`. Empty when a turn ends by the next one starting.
37
+ reasoning_start, reasoning_end (str): The tags around reasoning, such as `"<think>"` and
38
+ `"</think>"`. Empty when the family has no reasoning block.
39
+ tool_parser (ToolParser | None): The grammar the family writes tool calls in; `None` when
40
+ it has none.
41
+ stop (tuple[str, ...]): Every token the model may stop on; the server gets them as stop ids.
42
+ kwargs (tuple[str, ...]): Keyword arguments the template reads, such as `enable_thinking`;
43
+ HF passes them as `**kwargs`, the wire as `chat_template_kwargs`, and any other name
44
+ is a mistake the template would swallow.
45
+ models (tuple[str, ...]): Checkpoints the family was verified against; the tokenizer
46
+ tests run over them.
47
+ """
48
+
49
+ name: ClassVar[str] = ""
50
+ turn_end: ClassVar[str] = ""
51
+ reasoning_start: ClassVar[str] = ""
52
+ reasoning_end: ClassVar[str] = ""
53
+ tool_parser: ClassVar[ToolParser | None] = None
54
+ stop: ClassVar[tuple[str, ...]] = ()
55
+ kwargs: ClassVar[tuple[str, ...]] = ()
56
+ models: ClassVar[tuple[str, ...]] = ()
57
+
58
+ def __init__(self, tokenizer: PreTrainedTokenizerBase, **kwargs: Any) -> None:
59
+ self.tokenizer = tokenizer
60
+ if unknown := set(kwargs) - set(self.kwargs):
61
+ raise ValueError(f"{self.name or type(self).__name__} takes no kwarg named {sorted(unknown)}")
62
+ self._kwargs = kwargs
63
+ self.stop_ids = frozenset(self.token_id(s) for s in self.stop)
64
+
65
+ def encode(self, text: str) -> list[int]:
66
+ """Never adds special tokens: the template already wrote the ones it wants."""
67
+ return cast(list[int], self.tokenizer.encode(text, add_special_tokens=False))
68
+
69
+ def token_id(self, token: str) -> int:
70
+ """Input `token` has to be exactly one token here, or the family and the tokenizer do not match."""
71
+ ids = self.encode(token)
72
+ if len(ids) != 1:
73
+ raise ValueError(f"{token!r} is {len(ids)} tokens for this tokenizer, not one")
74
+ return ids[0]
75
+
76
+ def order_tool_results(self, messages: list[dict[str, Any]]) -> None:
77
+ """Put each run of tool results in its calls' order, in place, and refuse any other arrangement.
78
+
79
+ OpenAI's rule: a result follows the assistant turn whose call it answers, one result per
80
+ call, nothing in between. Templates without call ids pair the two by position, so any
81
+ other arrangement mispairs them without a word. A turn with no results yet passes; the
82
+ stub renders one.
83
+ """
84
+ i = 0
85
+ while i < len(messages):
86
+ message = messages[i]
87
+ i += 1
88
+ if message["role"] == "tool":
89
+ raise ValueError(f"tool result {message['tool_call_id']!r} does not follow the calls it answers")
90
+ if calls := message.get("tool_calls"):
91
+ order = [call["id"] for call in calls]
92
+ j = i
93
+ while j < len(messages) and messages[j]["role"] == "tool":
94
+ j += 1
95
+ results = messages[i:j]
96
+ if results and sorted(r["tool_call_id"] for r in results) != sorted(order):
97
+ raise ValueError(
98
+ f"tool results {[r['tool_call_id'] for r in results]} do not answer {order} one each"
99
+ )
100
+ messages[i:j] = sorted(results, key=lambda r: order.index(r["tool_call_id"]))
101
+ i = j
102
+
103
+ def conform(self, messages: list[Message]) -> list[dict[str, Any]]:
104
+ """Copy `messages` into the shape HF templates read: `arguments` as dicts, tool results in their calls' order."""
105
+ copies = cast(list[dict[str, Any]], copy.deepcopy(messages))
106
+ for call in (c for m in copies for c in m.get("tool_calls") or []):
107
+ if isinstance(call["function"]["arguments"], str):
108
+ call["function"]["arguments"] = json.loads(call["function"]["arguments"])
109
+ self.order_tool_results(copies)
110
+ return copies
111
+
112
+ def apply(
113
+ self,
114
+ messages: list[Message],
115
+ tools: list[ToolSchema] | None = None,
116
+ *,
117
+ add_generation_prompt: bool = True,
118
+ ) -> str:
119
+ """Apply the tokenizer's built-in chat template with this family's argument shape and kwargs baked in."""
120
+ text = self.tokenizer.apply_chat_template(
121
+ self.conform(messages),
122
+ tools=cast(Any, tools) or None,
123
+ add_generation_prompt=add_generation_prompt,
124
+ tokenize=False,
125
+ **self._kwargs,
126
+ )
127
+ return cast(str, text)
128
+
129
+ def stub(self, messages: list[PromptMessage], tool_calls: Iterable[ToolCall] | None) -> list[Message]:
130
+ """A stub history to put before `messages` so the template renders them; tool results get the assistant whose calls they answer."""
131
+ stub: list[Message] = [
132
+ SystemMessage(role="system", content="tokin-stub-system"),
133
+ UserMessage(role="user", content="tokin-stub-user"),
134
+ ]
135
+ if messages[0]["role"] == "tool":
136
+ if not tool_calls:
137
+ raise ChatTemplateError("tool results need the tool_calls they answer")
138
+ # A non-empty reasoning keeps the think block in place whether or not this turn is the last one.
139
+ stub.append(
140
+ AssistantMessage(role="assistant", content="", reasoning_content=" ", tool_calls=list(tool_calls))
141
+ )
142
+ return stub
143
+
144
+ def apply_after_stub(
145
+ self,
146
+ messages: list[PromptMessage],
147
+ tools: list[ToolSchema] | None = None,
148
+ *,
149
+ tool_calls: Iterable[ToolCall] | None = None,
150
+ add_generation_prompt: bool,
151
+ ) -> str:
152
+ """Apply the chat template to `messages` alone by rendering them after a stub history and subtracting it."""
153
+ stub = self.stub(messages, tool_calls)
154
+ roles = [m["role"] for m in messages]
155
+ try:
156
+ before = self.apply(stub, tools, add_generation_prompt=False)
157
+ after = self.apply([*stub, *messages], tools, add_generation_prompt=add_generation_prompt)
158
+ except Exception as e:
159
+ raise ChatTemplateError(f"template refuses {roles}: {e}") from e
160
+ if not after.startswith(before):
161
+ raise ChatTemplateError(f"template rewrites earlier turns when appending {roles}")
162
+ return after[len(before) :]
163
+
164
+ def apply_increment(
165
+ self,
166
+ messages: list[PromptMessage],
167
+ tools: list[ToolSchema] | None = None,
168
+ *,
169
+ tool_calls: Iterable[ToolCall] | None = None,
170
+ ) -> str:
171
+ """Apply the chat template to `messages` as the next increment of a multi-turn rollout."""
172
+ results = list(itertools.takewhile(lambda m: m["role"] == "tool", messages))
173
+ rest = messages[len(results) :]
174
+ if any(m["role"] == "tool" for m in rest):
175
+ raise ChatTemplateError("tool results come before any other message")
176
+ text = self.turn_end
177
+ if results:
178
+ text += self.apply_after_stub(results, tools, tool_calls=tool_calls, add_generation_prompt=not rest)
179
+ if rest:
180
+ text += self.apply_after_stub(rest, tools, add_generation_prompt=True)
181
+ # The model stopped on the token that opens the increment, so the prompt already has it.
182
+ for s in self.stop:
183
+ if text.startswith(s):
184
+ return text[len(s) :]
185
+ raise ChatTemplateError(f"the increment opens with {text[:16]!r}, which the model never stops on")
186
+
187
+ def parse(
188
+ self, response: str, tools: list[ToolSchema] | None = None, *, reasoning_open: bool = False
189
+ ) -> AssistantMessage:
190
+ """Read back the assistant message from what the model sampled.
191
+
192
+ Args:
193
+ response (str): The sampled text without its stop token.
194
+ tools (list[ToolSchema] | None): The schemas the calls may name; XML grammars type
195
+ their argument values by them.
196
+ reasoning_open (bool): The prompt wrote `reasoning_start` and not `reasoning_end`, so
197
+ `response` begins inside the reasoning block.
198
+ """
199
+ text = response.lstrip()
200
+ message: AssistantMessage = {"role": "assistant", "content": None}
201
+ if self.reasoning_end and (reasoning_open or text.startswith(self.reasoning_start)):
202
+ head, _, text = text.partition(self.reasoning_end)
203
+ if reasoning := head.removeprefix(self.reasoning_start).strip():
204
+ message["reasoning_content"] = reasoning
205
+ if self.tool_parser:
206
+ text, calls = self.tool_parser.parse(text, tools)
207
+ if calls:
208
+ message["tool_calls"] = calls
209
+ if content := text.strip():
210
+ message["content"] = content
211
+ return message
@@ -0,0 +1,23 @@
1
+ from ..tool_parsers import GLMToolParser
2
+ from .chat_template import ChatTemplate
3
+
4
+
5
+ class GLMChatTemplate(ChatTemplate):
6
+ name = "glm"
7
+ reasoning_start = "<think>"
8
+ reasoning_end = "</think>"
9
+ tool_parser = GLMToolParser()
10
+ stop = ("<|user|>", "<|observation|>", "<|endoftext|>")
11
+ kwargs = ("enable_thinking", "clear_thinking", "reasoning_effort")
12
+ models = (
13
+ "zai-org/GLM-4.5",
14
+ "zai-org/GLM-4.5-Air",
15
+ "zai-org/GLM-4.6",
16
+ "zai-org/GLM-4.7",
17
+ "zai-org/GLM-4.7-Flash",
18
+ "zai-org/GLM-5",
19
+ "zai-org/GLM-5.1",
20
+ "zai-org/GLM-5.2",
21
+ "zai-org/GLM-5.3",
22
+ "zai-org/GLM-5.3-Flash",
23
+ )
@@ -0,0 +1,70 @@
1
+ from ..tool_parsers import HermesToolParser, QwenXMLToolParser
2
+ from .chat_template import ChatTemplate
3
+
4
+
5
+ class QwenChatTemplate(ChatTemplate):
6
+ """Qwen2.5 through Qwen3, which write tool calls as JSON inside `<tool_call>`."""
7
+
8
+ name = "qwen"
9
+ turn_end = "<|im_end|>\n"
10
+ reasoning_start = "<think>"
11
+ reasoning_end = "</think>"
12
+ tool_parser = HermesToolParser()
13
+ stop = ("<|im_end|>", "<|endoftext|>")
14
+ kwargs = ("enable_thinking",)
15
+ models = (
16
+ "Qwen/Qwen2.5-0.5B",
17
+ "Qwen/Qwen2.5-1.5B",
18
+ "Qwen/Qwen2.5-3B",
19
+ "Qwen/Qwen2.5-7B",
20
+ "Qwen/Qwen2.5-14B",
21
+ "Qwen/Qwen2.5-32B",
22
+ "Qwen/Qwen2.5-72B",
23
+ "Qwen/Qwen2.5-0.5B-Instruct",
24
+ "Qwen/Qwen2.5-1.5B-Instruct",
25
+ "Qwen/Qwen2.5-3B-Instruct",
26
+ "Qwen/Qwen2.5-7B-Instruct",
27
+ "Qwen/Qwen2.5-14B-Instruct",
28
+ "Qwen/Qwen2.5-32B-Instruct",
29
+ "Qwen/Qwen2.5-72B-Instruct",
30
+ "Qwen/Qwen3-0.6B",
31
+ "Qwen/Qwen3-1.7B",
32
+ "Qwen/Qwen3-4B",
33
+ "Qwen/Qwen3-8B",
34
+ "Qwen/Qwen3-14B",
35
+ "Qwen/Qwen3-32B",
36
+ "Qwen/Qwen3-30B-A3B",
37
+ "Qwen/Qwen3-235B-A22B",
38
+ "Qwen/Qwen3-4B-Instruct-2507",
39
+ "Qwen/Qwen3-30B-A3B-Instruct-2507",
40
+ "Qwen/Qwen3-235B-A22B-Instruct-2507",
41
+ "Qwen/Qwen3-4B-Thinking-2507",
42
+ "Qwen/Qwen3-30B-A3B-Thinking-2507",
43
+ "Qwen/Qwen3-235B-A22B-Thinking-2507",
44
+ )
45
+
46
+
47
+ class Qwen35ChatTemplate(ChatTemplate):
48
+ """Qwen3.5 onwards, which write tool calls as `<function=…>` XML inside `<tool_call>`."""
49
+
50
+ name = "qwen35"
51
+ turn_end = "<|im_end|>\n"
52
+ reasoning_start = "<think>"
53
+ reasoning_end = "</think>"
54
+ tool_parser = QwenXMLToolParser()
55
+ stop = ("<|im_end|>", "<|endoftext|>")
56
+ kwargs = ("enable_thinking", "preserve_thinking", "add_vision_id")
57
+ models = (
58
+ "Qwen/Qwen3.5-0.8B",
59
+ "Qwen/Qwen3.5-2B",
60
+ "Qwen/Qwen3.5-4B",
61
+ "Qwen/Qwen3.5-9B",
62
+ "Qwen/Qwen3.5-27B",
63
+ "Qwen/Qwen3.5-35B-A3B",
64
+ "Qwen/Qwen3.5-122B-A10B",
65
+ "Qwen/Qwen3.5-397B-A17B",
66
+ "Qwen/Qwen3.6-27B",
67
+ "Qwen/Qwen3.6-35B-A3B",
68
+ "Qwen/Qwen3.8-27B",
69
+ "Qwen/Qwen3.8-2.4T-A95B",
70
+ )
tokin/py.typed ADDED
File without changes
tokin/rollout.py ADDED
@@ -0,0 +1,59 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass, field
4
+
5
+
6
+ @dataclass
7
+ class Turn:
8
+ """A contiguous run of token ids, either from the prompt or sampled by the model."""
9
+
10
+ token_ids: list[int]
11
+ generated: bool
12
+ logprobs: list[float] | None = None
13
+
14
+ def __post_init__(self) -> None:
15
+ # Whether logprobs are required is the trainer's call; alignment is not.
16
+ if self.logprobs is not None and len(self.logprobs) != len(self.token_ids):
17
+ raise ValueError(f"logprobs has {len(self.logprobs)} entries but token_ids has {len(self.token_ids)}")
18
+
19
+ def __len__(self) -> int:
20
+ return len(self.token_ids)
21
+
22
+
23
+ @dataclass
24
+ class Rollout:
25
+ """The turns of one conversation, in order."""
26
+
27
+ turns: list[Turn] = field(default_factory=list)
28
+
29
+ def add_prompt(self, token_ids: list[int]) -> None:
30
+ """Add prompt (input) tokens."""
31
+ # A zero-length turn adds no tokens but still reads as a segment boundary.
32
+ if token_ids:
33
+ self.turns.append(Turn(token_ids=list(token_ids), generated=False))
34
+
35
+ def add_response(self, token_ids: list[int], logprobs: list[float] | None = None) -> None:
36
+ """Add model-generated (output) tokens."""
37
+ if not token_ids:
38
+ return
39
+ if not self.turns:
40
+ raise RuntimeError("a rollout cannot open with a generated turn; add_prompt first")
41
+ self.turns.append(
42
+ Turn(
43
+ token_ids=list(token_ids),
44
+ generated=True,
45
+ logprobs=None if logprobs is None else list(logprobs),
46
+ )
47
+ )
48
+
49
+ @property
50
+ def token_ids(self) -> list[int]:
51
+ """Every turn's ids concatenated — the prefix the next prompt extends."""
52
+ return [i for turn in self.turns for i in turn.token_ids]
53
+
54
+ def __len__(self) -> int:
55
+ return sum(len(turn) for turn in self.turns)
56
+
57
+ def __repr__(self) -> str:
58
+ generated = sum(len(t) for t in self.turns if t.generated)
59
+ return f"Rollout(turns={len(self.turns)}, tokens={len(self)}, generated={generated})"
tokin/session.py ADDED
@@ -0,0 +1,35 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass, field
4
+
5
+ from .rollout import Rollout
6
+
7
+
8
+ @dataclass
9
+ class Session:
10
+ """One agent run, as the rollouts it produced.
11
+
12
+ Usually one: turns append to it in place. A harness that rewrites history —
13
+ context compaction, a re-rendered prior turn — breaks the prefix the next
14
+ prompt would extend, and the run continues in a fresh rollout via `fork`.
15
+ Every rollout here shares an outcome, which is what lets a trainer weight the
16
+ run once rather than once per fork.
17
+ """
18
+
19
+ rollouts: list[Rollout] = field(default_factory=lambda: [Rollout()])
20
+
21
+ @property
22
+ def current(self) -> Rollout:
23
+ """The rollout new turns append to."""
24
+ return self.rollouts[-1]
25
+
26
+ def fork(self) -> Rollout:
27
+ """Start a fresh rollout, leaving the previous one closed but trainable."""
28
+ self.rollouts.append(Rollout())
29
+ return self.rollouts[-1]
30
+
31
+ def __len__(self) -> int:
32
+ return sum(len(rollout) for rollout in self.rollouts)
33
+
34
+ def __repr__(self) -> str:
35
+ return f"Session(rollouts={len(self.rollouts)}, tokens={len(self)})"
@@ -0,0 +1,6 @@
1
+ from .glm import GLMToolParser
2
+ from .hermes import HermesToolParser
3
+ from .qwen_xml import QwenXMLToolParser
4
+ from .tool_parser import TOOL_CALL, ToolParser
5
+
6
+ __all__ = ["TOOL_CALL", "GLMToolParser", "HermesToolParser", "QwenXMLToolParser", "ToolParser"]
@@ -0,0 +1,23 @@
1
+ import re
2
+
3
+ from ..types import FunctionToolCall, ToolSchema
4
+ from .tool_parser import TOOL_CALL, ToolParser
5
+
6
+
7
+ class GLMToolParser(ToolParser):
8
+ """GLM-4.5's grammar; every GLM since writes it, one tag per line before 4.7.
9
+
10
+ `<tool_call>f<arg_key>x</arg_key><arg_value>1</arg_value></tool_call>`
11
+ """
12
+
13
+ block = TOOL_CALL
14
+ identifier = re.compile(r"[\w.\-]+")
15
+ pair = re.compile(r"<arg_key>(.*?)</arg_key>\s*<arg_value>(.*?)</arg_value>", re.DOTALL)
16
+
17
+ def parse_block(self, body: str, tools: list[ToolSchema] | None) -> list[FunctionToolCall] | None:
18
+ name, _, arguments = body.partition("<arg_key>")
19
+ name = name.strip()
20
+ if not self.identifier.fullmatch(name):
21
+ return None
22
+ pairs = self.pair.findall("<arg_key>" + arguments) if arguments else []
23
+ return [self.tool_call(name, {k.strip(): self.coerce(v, tools, name, k.strip()) for k, v in pairs})]
@@ -0,0 +1,25 @@
1
+ import json
2
+
3
+ from ..types import FunctionToolCall, ToolSchema
4
+ from .tool_parser import TOOL_CALL, ToolParser
5
+
6
+
7
+ class HermesToolParser(ToolParser):
8
+ """Hermes 2 Pro's grammar; Qwen2.5 and Qwen3 write it.
9
+
10
+ `<tool_call>{"name": "f", "arguments": {"x": 1}}</tool_call>`
11
+ """
12
+
13
+ block = TOOL_CALL
14
+
15
+ def parse_block(self, body: str, tools: list[ToolSchema] | None) -> list[FunctionToolCall] | None:
16
+ try:
17
+ call = json.loads(body)
18
+ arguments = call.get("arguments") if isinstance(call, dict) else None
19
+ if isinstance(arguments, str):
20
+ arguments = json.loads(arguments)
21
+ except ValueError:
22
+ return None
23
+ if isinstance(call, dict) and isinstance(call.get("name"), str) and isinstance(arguments, dict):
24
+ return [self.tool_call(call["name"], arguments)]
25
+ return None
@@ -0,0 +1,22 @@
1
+ import re
2
+
3
+ from ..types import FunctionToolCall, ToolSchema
4
+ from .tool_parser import TOOL_CALL, ToolParser
5
+
6
+
7
+ class QwenXMLToolParser(ToolParser):
8
+ """Qwen3-Coder's grammar; Qwen3.5 onwards writes it, one tag per line.
9
+
10
+ `<tool_call><function=f><parameter=x>1</parameter></function></tool_call>`
11
+ """
12
+
13
+ block = TOOL_CALL
14
+ function = re.compile(r"\A<function=([^>\n]+)>(.*)</function>\Z", re.DOTALL)
15
+ parameter = re.compile(r"<parameter=([^>\n]+)>\n?(.*?)\n?</parameter>", re.DOTALL)
16
+
17
+ def parse_block(self, body: str, tools: list[ToolSchema] | None) -> list[FunctionToolCall] | None:
18
+ if not (m := self.function.match(body.strip())):
19
+ return None
20
+ name, parameters = m.groups()
21
+ arguments = {k: self.coerce(v, tools, name, k) for k, v in self.parameter.findall(parameters)}
22
+ return [self.tool_call(name, arguments)]
@@ -0,0 +1,52 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import re
5
+ import uuid
6
+ from typing import Any, ClassVar
7
+
8
+ from ..types import FunctionToolCall, ToolSchema
9
+
10
+ TOOL_CALL = re.compile(r"<tool_call>\n?(.*?)\n?</tool_call>", re.DOTALL)
11
+
12
+
13
+ class ToolParser:
14
+ """One tool-call grammar: `block` finds the calls in a response, `parse_block` turns a block's body into calls."""
15
+
16
+ block: ClassVar[re.Pattern[str]]
17
+
18
+ def parse_block(self, body: str, tools: list[ToolSchema] | None) -> list[FunctionToolCall] | None:
19
+ """The calls in one block, or `None` when the body is not in this grammar."""
20
+ raise NotImplementedError
21
+
22
+ def parse(self, text: str, tools: list[ToolSchema] | None) -> tuple[str, list[FunctionToolCall]]:
23
+ """Cut every block `parse_block` understands out of `text`; one it does not stays as the model wrote it."""
24
+ calls: list[FunctionToolCall] = []
25
+
26
+ def replace(m: re.Match[str]) -> str:
27
+ if (found := self.parse_block(m.group(1), tools)) is None:
28
+ return m.group(0)
29
+ calls.extend(found)
30
+ return ""
31
+
32
+ return self.block.sub(replace, text), calls
33
+
34
+ def coerce(self, value: str, tools: list[ToolSchema] | None, name: str, key: str) -> Any:
35
+ """A tag body typed by the tool's schema: strings stay text, anything else is JSON when it parses as JSON."""
36
+ for tool in tools or []:
37
+ if tool["function"]["name"] == name:
38
+ properties = tool["function"].get("parameters", {}).get("properties")
39
+ if isinstance(properties, dict) and properties.get(key, {}).get("type") == "string":
40
+ return value
41
+ try:
42
+ return json.loads(value)
43
+ except ValueError:
44
+ return value
45
+
46
+ def tool_call(self, name: str, arguments: dict[str, Any], id: str | None = None) -> FunctionToolCall:
47
+ """An OpenAI tool call; `id` is the model's when the grammar carries one, as Mistral's does, minted otherwise."""
48
+ return FunctionToolCall(
49
+ id=id or f"call_{uuid.uuid4().hex[:24]}",
50
+ type="function",
51
+ function={"name": name, "arguments": json.dumps(arguments, ensure_ascii=False)},
52
+ )
tokin/types.py ADDED
@@ -0,0 +1,35 @@
1
+ from __future__ import annotations
2
+
3
+ from openai.types.chat import (
4
+ ChatCompletionAssistantMessageParam as _AssistantMessage,
5
+ ChatCompletionDeveloperMessageParam as DeveloperMessage,
6
+ ChatCompletionMessageFunctionToolCallParam as FunctionToolCall,
7
+ ChatCompletionMessageToolCallUnionParam as ToolCall,
8
+ ChatCompletionSystemMessageParam as SystemMessage,
9
+ ChatCompletionToolMessageParam as ToolMessage,
10
+ ChatCompletionToolParam as ToolSchema,
11
+ ChatCompletionUserMessageParam as UserMessage,
12
+ )
13
+
14
+
15
+ class AssistantMessage(_AssistantMessage, total=False):
16
+ """OpenAI's assistant message plus the field reasoning models keep their thinking in."""
17
+
18
+ reasoning_content: str
19
+
20
+
21
+ type PromptMessage = DeveloperMessage | SystemMessage | UserMessage | ToolMessage
22
+ type Message = PromptMessage | AssistantMessage
23
+
24
+ __all__ = [
25
+ "AssistantMessage",
26
+ "DeveloperMessage",
27
+ "FunctionToolCall",
28
+ "Message",
29
+ "PromptMessage",
30
+ "SystemMessage",
31
+ "ToolCall",
32
+ "ToolMessage",
33
+ "ToolSchema",
34
+ "UserMessage",
35
+ ]
@@ -0,0 +1,38 @@
1
+ Metadata-Version: 2.5
2
+ Name: tokin
3
+ Version: 0.0.1
4
+ Summary: Make any agent harness token-native.
5
+ Project-URL: Homepage, https://github.com/camel-ai/tokin
6
+ Project-URL: Repository, https://github.com/camel-ai/tokin
7
+ Project-URL: Issues, https://github.com/camel-ai/tokin/issues
8
+ Author-email: Yuan He <yuanhe.cs.ai@gmail.com>
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Programming Language :: Python :: 3.14
18
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
19
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.12
22
+ Requires-Dist: aiohttp>=3.10
23
+ Requires-Dist: jinja2>=3.1
24
+ Requires-Dist: openai>=2
25
+ Requires-Dist: transformers>=5.6
26
+ Description-Content-Type: text/markdown
27
+
28
+ # tokin
29
+ Make any agent harness token-native.
30
+
31
+ <p align="center">
32
+ <img src="assets/architecture.svg" alt="The harness sends messages to tokin and gets back text and tool calls. tokin sends input_ids to the inference server and gets back output_ids and logprobs." width="100%">
33
+ </p>
34
+
35
+ The harness keeps speaking text over a standard chat-completions API. The inference
36
+ server only ever receives token ids. tokin owns the chat template in between, so the
37
+ ids a model generated on one turn are the ids the next turn's prompt carries — no
38
+ detokenize/retokenize round trip, no silent drift.
@@ -0,0 +1,18 @@
1
+ tokin/__init__.py,sha256=n6TrmmNmtYXPDqMUVPmmRs6v0zxdR_HhVL2KVV0M3U8,329
2
+ tokin/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ tokin/rollout.py,sha256=GzNigkujtYhaEt1sM2ziSxb9e5GOLm7sOddOEsgNmRM,2086
4
+ tokin/session.py,sha256=G7VKMplrEokuZkkwBtRvFKwNgf7WZR8y2k_8l9j7Xis,1151
5
+ tokin/types.py,sha256=cvXKgjlug5KDfqz08P5U-EJDlTy5itx5dwEtz0q_9YQ,1045
6
+ tokin/chat_templates/__init__.py,sha256=xMmqKL8hi2at9kld62LnwWj43jcP9uyJrChEwyev9M0,1126
7
+ tokin/chat_templates/chat_template.py,sha256=aHKsnQvyZtg2nHtpPVd5RcUAY9IaPVSIkBbjRcIXp_I,9752
8
+ tokin/chat_templates/glm.py,sha256=P5G-TTkCpiaMw0LU80vAO14R_cTYveXITDQVYaba34o,670
9
+ tokin/chat_templates/qwen.py,sha256=7owsrnKB7bUBvV0cBfy4nW2uNo-dsnZ9mHEg07vWEfs,2192
10
+ tokin/tool_parsers/__init__.py,sha256=NxCnfbKbseCO60klsBso4EIbhy2X317PyO_FOObA0Z4,252
11
+ tokin/tool_parsers/glm.py,sha256=470_GFbfc-zelpmMu5cHUu64Fv0lKxlWgLkVrFxthFk,915
12
+ tokin/tool_parsers/hermes.py,sha256=gq1K0WUq0Da1YoXvJej6L5NiYHUkgLSTMz5N6cajXww,869
13
+ tokin/tool_parsers/qwen_xml.py,sha256=vqtAPSOhmpKYmXX0KEJeZNxoGIEjQT_MQc1TAAE8EPk,875
14
+ tokin/tool_parsers/tool_parser.py,sha256=jl1JcDP_kbJcbUCtmxV3urGvS0GQZoD16DLL8pVR4yA,2214
15
+ tokin-0.0.1.dist-info/METADATA,sha256=Dz8VQY7EVt29e-VZl9vXWJPbr_hA9-bqjb4ylpMPoVY,1651
16
+ tokin-0.0.1.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
17
+ tokin-0.0.1.dist-info/licenses/LICENSE,sha256=-y2tMt63zcy-M_uFb_pS0HzkGf5I0qeeD76mspGMIOk,11344
18
+ tokin-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 @ CAMEL-AI.org
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.