Repository navigation
Expand file tree
/
Copy pathsdk_py_client_gen.py
More file actions
135 lines (116 loc) · 5.28 KB
/
Copy pathsdk_py_client_gen.py
File metadata and controls
135 lines (116 loc) · 5.28 KB
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
132
133
134
135
"""Generate `sdk/python/loom/client.py` — one Python method per served op — from
the server's registry (the TypeScript twin is the `LoomClient` group accessors
over `sdk/typescript/src/generated/ops.ts`).
`agent.client.<group>.<method>(body, **options)` is `agent.call("<group>.<rest>",
body, **options)`: the group is the op name's first segment and the method is
the rest with `.` turned into `_` (`tracker.source.add` → `tracker.source_add`),
the snake_case spelling of the TypeScript `loom.tracker.sourceAdd`; a method that
is a Python keyword takes a trailing underscore (`memory.import` →
`memory.import_`, TypeScript `loom.memory.import`). Each method
is typed with the op's `<Op>Body` and `<Op>Output` from `loom.ops`, so a new
server op reaches both SDKs by regeneration alone. The hand-written clients
(`agent.memory`, `agent.tasks`, …) stay the high-level layer on top.
python scripts/codegen/sdk_py_client_gen.py # write the file
python scripts/codegen/sdk_py_client_gen.py --check # exit 1 when the file is stale (CI)
"""
from __future__ import annotations
import json
import keyword
import sys
from collections import defaultdict
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
if str(ROOT) not in sys.path: # run as a file
sys.path.insert(0, str(ROOT))
from scripts.codegen.common import ( # noqa: E402
GeneratedFile,
generator_main,
pascal,
ruff_format,
)
from scripts.codegen.sdk_py_gen import op_rows # noqa: E402
COMMAND = "python scripts/codegen/sdk_py_client_gen.py"
def split_op(name: str) -> tuple[str, str]:
"""`tracker.source.add` → (`tracker`, `source_add`): the group attribute and
the method both SDKs expose it as (TypeScript camel-cases the method). A
method that is a Python keyword is spelled as PEP 8 spells such a name, with a
trailing underscore (`memory.import` → `import_`)."""
group, _, rest = name.partition(".")
method = rest.replace(".", "_")
if keyword.iskeyword(method):
method += "_"
if not (group.isidentifier() and method.isidentifier()):
raise SystemExit(f"op {name!r} has no valid Python method name")
return group, method
def build() -> str:
_, rows = op_rows()
groups: dict[str, list[tuple[str, str, str, str]]] = defaultdict(list)
for facts, _in_name, body_name, out_name in rows:
group, method = split_op(facts.name)
if any(m == method for m, *_ in groups[group]):
raise SystemExit(f"two ops map to {group}.{method}")
groups[group].append((method, facts.name, body_name, out_name))
out: list[str] = [
'"""GENERATED by scripts/codegen/sdk_py_client_gen.py from server.operations.registry.ALL_OPERATIONS — do not edit.', # noqa: E501
"",
"One method per served operation, grouped by the op name's first segment:",
'`agent.client.<group>.<method>(body)` is `agent.call("<group>.<rest>", body)`',
"(`tracker.source.add` → `agent.client.tracker.source_add`),",
"with the identity filled in by the Agent and `**options` passed through",
"(`user_id`, `session_id`, `run_id`, `agent_id`, `idempotency_key`, `timeout_s`,",
"`retry`, or any extra wire field). The TypeScript SDK exposes the same ops as",
"`loom.tracker.sourceAdd(input)`. Regenerate:",
f"{COMMAND} (CI: --check).",
'"""',
"# ruff: noqa: E501",
"",
"from __future__ import annotations",
"",
"from typing import TYPE_CHECKING, Any, cast",
"",
"from loom import ops as _ops",
"",
"if TYPE_CHECKING:",
" from loom.agent import Agent",
"",
'__all__ = ["OpsClient"]',
"",
]
for group in sorted(groups):
out += [
"",
f"class {pascal(group)}Ops:",
f' """The `{group}.*` operations."""',
"",
" # SyncAgent proxies a nested client's coroutines as blocking calls.",
" _loom_nested_client = True",
"",
" def __init__(self, agent: Agent) -> None:",
" self._agent = agent",
]
for method, name, body_name, out_name in groups[group]:
out += [
"",
f" async def {method}(",
f" self, body: _ops.{body_name} | None = None, /, **options: Any",
f" ) -> _ops.{out_name}:",
f' """`{name}`."""',
f' return cast("_ops.{out_name}", await self._agent.call({json.dumps(name)}, body, **options))', # noqa: E501
]
out += [
"",
"",
"class OpsClient:",
' """Every served operation as a method: `agent.client.<group>.<method>(...)`."""',
"",
" def __init__(self, agent: Agent) -> None:",
]
out += [f" self.{g} = {pascal(g)}Ops(agent)" for g in sorted(groups)]
return _ruff_format("\n".join(out).rstrip("\n") + "\n")
def _ruff_format(text: str) -> str:
return ruff_format(text, "client.py")
TARGET = GeneratedFile(ROOT / "sdk" / "python" / "loom" / "client.py", COMMAND, _ruff_format)
def main(argv: list[str] | None = None) -> int:
return generator_main(__doc__, TARGET, build, argv)
if __name__ == "__main__":
raise SystemExit(main())