lmcc 0.8.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.
lmcc/__init__.py ADDED
@@ -0,0 +1,46 @@
1
+ """lmcc — the language model calling convention.
2
+
3
+ A typed signature and an adapter (a template, a parse rule, transports by
4
+ purpose, formats by type) bind into a plan that renders messages and parses
5
+ replies. The kernel ships no vocabulary beyond its scalar and media
6
+ defaults; everything else registers through the sockets.
7
+ """
8
+
9
+ from .adapter import (Adapter, adapter, assistant, developer, message, system, turns, use,
10
+ user)
11
+ from .core import (Field, SignatureCore, Capture, field, signature, signature_from_dict,
12
+ signature_to_dict, typename)
13
+ from .errors import Refusal, refuse
14
+ from .extensions import ExtensionBinding, PatternBinding, native_extensions
15
+ from .fn import Fn, One, Purpose, fn
16
+ from .formats import Format, make as make_format, ship
17
+ from .reader import Reader
18
+ from .plan import Plan, Reading, RenderResult, bind
19
+ from .helpers import choose, find, put, when
20
+ from .registry import Registry, default_registry
21
+ from .serde import KERNEL_VERSION, dump, load
22
+ from .transport import Transport
23
+ from .stream import Stream, StreamResult
24
+ from .turn import ModelStep, ToolStep, Turn, signature_fingerprint
25
+
26
+ __version__ = KERNEL_VERSION
27
+
28
+
29
+
30
+ def format(host_type, **kw):
31
+ """``lmcc.format(Person, write=..., read=..., describe=...)`` — bind a
32
+ type to a format in the default registry (per runtime, never
33
+ serialized; ``ship`` does that on request)."""
34
+ return default_registry.format(host_type, **kw)
35
+
36
+
37
+ __all__ = [
38
+ "Adapter", "ExtensionBinding", "Field", "Fn", "Format", "KERNEL_VERSION", "Reader",
39
+ "ModelStep", "One", "PatternBinding", "Plan", "Reading",
40
+ "Refusal", "Registry", "RenderResult", "Purpose", "SignatureCore", "Capture", "Transport",
41
+ "Stream", "StreamResult", "ToolStep", "Turn",
42
+ "adapter", "assistant", "bind", "choose", "find", "put", "when", "default_registry", "developer", "dump",
43
+ "field", "fn", "format", "load", "make_format", "message", "native_extensions",
44
+ "refuse", "ship", "signature", "signature_fingerprint",
45
+ "signature_from_dict", "signature_to_dict", "system", "turns", "typename", "use", "user",
46
+ ]
lmcc/adapter.py ADDED
@@ -0,0 +1,214 @@
1
+ """The Adapter: a template, a reader, transports by purpose, formats by
2
+ type — never a field name. It meets a signature only at ``bind``.
3
+
4
+ Construction surfaces:
5
+ - ``lmcc.adapter(messages=[...], reader=..., transports=..., formats=...)``
6
+ - ``lmcc.load(entry, registry=...)`` from serialized data (serde.py)
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from dataclasses import dataclass, field as dc_field
12
+
13
+ from .errors import refuse
14
+ from .transport import Transport
15
+ from .template import RESERVED_SLOTS, compile_template, turn_slots
16
+
17
+ _SLOT_NAME = __import__("re").compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
18
+ REPLAY = ("recorded", "values")
19
+
20
+
21
+ def system(text: str) -> dict:
22
+ return {"role": "system", "text": text}
23
+
24
+
25
+ def developer(text: str) -> dict:
26
+ return {"role": "developer", "text": text}
27
+
28
+
29
+ def user(text: str) -> dict:
30
+ return {"role": "user", "text": text}
31
+
32
+
33
+ def assistant(text: str) -> dict:
34
+ return {"role": "assistant", "text": text}
35
+
36
+
37
+ def message(role: str, text: str) -> dict:
38
+ if role not in ("system", "developer", "user", "assistant"):
39
+ refuse("entry-malformed", f"message role {role!r} must be system/developer/user/assistant",
40
+ fix={"action": "edit-entry", "path": "template"})
41
+ return {"role": role, "text": text}
42
+
43
+
44
+ def turns(slot: str = "turns") -> dict:
45
+ """A turn slot in messages form (kernel §3a): the slot's turns become
46
+ ordinary messages here. ``lmcc.turns()`` is the slot ``turns``."""
47
+ return {"directive": "turns"} if slot == "turns" else {"directive": "turns", "slot": slot}
48
+
49
+
50
+ def use(name: str, **options) -> dict:
51
+ """A reference to a named format or transport: ``lmcc.use("table", columns=[...])``."""
52
+ return {"use": name, "options": options}
53
+
54
+
55
+ @dataclass
56
+ class Adapter:
57
+ template: list # [{role, text} | {directive}]
58
+ reader: dict # {"kind": "derived", ...}
59
+ transports: dict[str, object] = dc_field(default_factory=dict) # purpose -> Transport | {"use", "options"}
60
+ formats: dict[str, object] = dc_field(default_factory=dict) # type/structural key -> {"use", "options"} | shipped dict | Format
61
+ name: str = "adapter"
62
+ extensions: dict[str, str] = dc_field(default_factory=dict) # "<family>/<name>" -> version needed (kernel §10)
63
+ replay: str = "recorded" # how written model steps are spelled (kernel §3a)
64
+ strict: bool = False # True: read replies exactly, no repairs (kernel §4a)
65
+
66
+ def bind(self, signature, capabilities: dict | None = None, *, registry=None):
67
+ from .plan import bind as _bind
68
+ from .registry import default_registry
69
+ return _bind(self, signature, capabilities or {}, registry or default_registry)
70
+
71
+
72
+ def dump(self, *, registry=None) -> dict:
73
+ from .serde import dump as _dump
74
+ from .registry import default_registry
75
+ return _dump(self, registry or default_registry)
76
+
77
+ def compiled_messages(self) -> list[tuple[dict, list | None]]:
78
+ cached = getattr(self, "_compiled", None)
79
+ if cached is not None and cached[0] == self.template:
80
+ return cached[1]
81
+ out = []
82
+ for i, msg in enumerate(self.template):
83
+ if "directive" in msg:
84
+ out.append((msg, None))
85
+ else:
86
+ out.append((msg, compile_template(msg["text"], where=f"template[{i}]")))
87
+ object.__setattr__(self, "_compiled", ([dict(m) for m in self.template], out))
88
+ return out
89
+
90
+ def turn_slots(self) -> dict[str, tuple[str, int]]:
91
+ """Every placed turn slot: name -> ("messages" | "text", template index)
92
+ (kernel §3a). Placing one twice, or guarding an unplaced one, is
93
+ ``template-syntax``."""
94
+ slots: dict[str, tuple[str, int]] = {}
95
+ guards: list[tuple[str, int]] = []
96
+ for i, (msg, nodes) in enumerate(self.compiled_messages()):
97
+ if nodes is None:
98
+ placed, guarded = [msg.get("slot", "turns")], []
99
+ form = "messages"
100
+ else:
101
+ placed, guarded = turn_slots(nodes)
102
+ form = "text"
103
+ for name in placed:
104
+ if name in slots:
105
+ refuse("template-syntax",
106
+ f"template[{i}]: turn slot {name!r} is already placed at "
107
+ f"template[{slots[name][1]}]; a slot is placed once",
108
+ fix={"action": "edit-template", "path": f"template[{i}]"})
109
+ slots[name] = (form, i)
110
+ guards += [(g, i) for g in guarded]
111
+ self._guards = guards # checked at bind: a guard may name an input (kernel §3a)
112
+ return slots
113
+
114
+
115
+ def adapter(*, messages: list[dict] | None = None, template: list[dict] | dict | None = None,
116
+ reader: dict | None = None, transports: dict | None = None,
117
+ formats: dict | None = None, name: str = "adapter",
118
+ extensions: dict[str, str] | None = None, replay: str = "recorded",
119
+ strict: bool = False, declare_defaults: bool = True) -> Adapter:
120
+ """Build an adapter. ``transports`` values: a name, a :class:`Transport`,
121
+ a data dict, or ``use(...)``. ``formats`` keys: type names or structural
122
+ keys; values: a name, ``use(...)``, a shipped dict, or a Format.
123
+ ``extensions``: ``{"<family>/<name>": version}`` the adapter needs
124
+ (kernel §10); checked against the registry at bind. With
125
+ ``declare_defaults`` (the constructor's convenience, not the loader's)
126
+ an inline ``pattern`` rule declares ``pattern/legacy-re2`` for you;
127
+ the dumped artifact carries the line either way. ``replay``:
128
+ ``"recorded"`` writes a past model step's recorded reply when this plan
129
+ reads it back into the same values, ``"values"`` always writes it from
130
+ its values (kernel §3a). ``strict=True`` reads replies exactly as the
131
+ template spells them: no marker, delimiter or value repairs (kernel §4a)."""
132
+ if messages is None:
133
+ messages = template.get("messages") if isinstance(template, dict) else template
134
+ if not isinstance(messages, list):
135
+ refuse("entry-malformed", "template must be a list of messages and directives",
136
+ fix={"action": "edit-entry", "path": "template"})
137
+ for i, m in enumerate(messages):
138
+ if not isinstance(m, dict) or not ({"role", "text"} <= set(m) or "directive" in m):
139
+ refuse("entry-malformed", f"template[{i}]: a message is {{role, text}} or {{directive}}",
140
+ fix={"action": "edit-entry", "path": f"template[{i}]"})
141
+ if "directive" in m:
142
+ slot = m.get("slot", "turns")
143
+ if (m["directive"] != "turns" or set(m) - {"directive", "slot"}
144
+ or not isinstance(slot, str) or not _SLOT_NAME.match(slot)):
145
+ refuse("entry-malformed",
146
+ f"template[{i}]: a directive is {{\"directive\": \"turns\", \"slot\"?: "
147
+ f"name}} (demos and history are turn slots since kernel 0.7)",
148
+ fix={"action": "edit-entry", "path": f"template[{i}]"})
149
+ if slot in RESERVED_SLOTS:
150
+ refuse("template-syntax", f"template[{i}]: {slot!r} is reserved, not a turn slot",
151
+ fix={"action": "edit-template", "path": f"template[{i}]"})
152
+ if "role" in m and m["role"] not in ("system", "developer", "user", "assistant"):
153
+ refuse("entry-malformed", f"template[{i}]: role must be system/developer/user/assistant",
154
+ fix={"action": "edit-entry", "path": f"template[{i}]"})
155
+ if m.get("role") == "system" and any("role" in x and x["role"] != "system" or "directive" in x
156
+ for x in messages[:i]):
157
+ refuse("entry-malformed",
158
+ f"template[{i}]: system messages lead the template (they become the lm15 "
159
+ f"request's system field); put later instructions in a developer message",
160
+ fix={"action": "edit-entry", "path": f"template[{i}]"})
161
+ if replay not in REPLAY:
162
+ refuse("entry-malformed", f"replay must be one of {REPLAY}, not {replay!r}",
163
+ fix={"action": "edit-entry", "path": "replay"})
164
+ reader = reader or {"kind": "derived"}
165
+ kind = reader.get("kind")
166
+ if not isinstance(kind, str) or not kind:
167
+ refuse("unknown-reader", "reader.kind must name a reader",
168
+ fix={"action": "edit-entry", "path": "reader"})
169
+ if kind == "derived" and set(reader) != {"kind"}:
170
+ refuse("entry-malformed", f"reader: the derived reader takes only 'kind', not "
171
+ f"{sorted(set(reader) - {'kind'})}",
172
+ fix={"action": "edit-entry", "path": "reader"})
173
+ if not isinstance(strict, bool):
174
+ refuse("entry-malformed", f"strict must be true or false, not {strict!r}",
175
+ fix={"action": "edit-entry", "path": "strict"})
176
+ s_bindings: dict[str, object] = {}
177
+ for purpose, value in (transports or {}).items():
178
+ where = f"transports[{purpose!r}]"
179
+ if isinstance(value, str):
180
+ s_bindings[purpose] = {"use": value, "options": {}}
181
+ elif isinstance(value, Transport):
182
+ value.validate(where=where)
183
+ s_bindings[purpose] = value
184
+ elif isinstance(value, dict) and "use" in value:
185
+ s_bindings[purpose] = {"use": value["use"], "options": dict(value.get("options", {}))}
186
+ elif isinstance(value, dict):
187
+ s_bindings[purpose] = Transport.from_dict(value, where=where)
188
+ else:
189
+ refuse("entry-malformed", f"{where}: expected a name, Transport, use(...), or dict",
190
+ fix={"action": "edit-entry", "path": where})
191
+ f_bindings: dict[str, object] = {}
192
+ for key, value in (formats or {}).items():
193
+ where = f"formats[{key!r}]"
194
+ if isinstance(value, str):
195
+ f_bindings[key] = {"use": value, "options": {}}
196
+ elif isinstance(value, dict) and "use" in value:
197
+ f_bindings[key] = {"use": value["use"], "options": dict(value.get("options", {}))}
198
+ elif isinstance(value, dict) and "language" in value:
199
+ f_bindings[key] = dict(value)
200
+ elif hasattr(value, "write"):
201
+ f_bindings[key] = value
202
+ else:
203
+ refuse("entry-malformed", f"{where}: expected a name, use(...), a shipped format, or a Format",
204
+ fix={"action": "edit-entry", "path": where})
205
+ from .extensions import default_declaration, validate_declaration
206
+ declared = validate_declaration(extensions)
207
+ if declare_defaults:
208
+ declared = default_declaration(s_bindings, declared)
209
+ adp = Adapter(template=list(messages), reader=dict(reader), transports=s_bindings,
210
+ formats=f_bindings, name=name, extensions=declared, replay=replay,
211
+ strict=strict)
212
+ adp.compiled_messages() # surface template syntax errors immediately
213
+ adp.turn_slots() # and turn-slot put errors
214
+ return adp