levier 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.
levier/__init__.py ADDED
@@ -0,0 +1,66 @@
1
+ """One import for Levier Apps and Runtimes.
2
+
3
+ Apps::
4
+
5
+ from levier import App, tool
6
+
7
+ @tool
8
+ def counter_add(delta: int) -> dict:
9
+ return {"value": delta}
10
+
11
+ app = App(tools=[counter_add], mcp=["github"])
12
+ app.run()
13
+
14
+ Runtimes::
15
+
16
+ from levier import Context, Runtime
17
+
18
+ async def run(ctx: Context) -> str:
19
+ tools = await ctx.toolbox()
20
+ reply = await ctx.chat(ctx.input, tools=tools)
21
+ await ctx.invoke_all(reply, toolbox=tools)
22
+ return "completed"
23
+
24
+ Runtime.start(run)
25
+
26
+ The heavy runtime SDK is imported lazily so an App-only installation stays
27
+ small and has no gRPC dependency.
28
+
29
+ Copyright 2026 The Levier Authors.
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ from typing import Any
35
+
36
+ from .app import App
37
+ from .tools import Tool, schema_from_function, tool
38
+
39
+ __version__ = "0.1.0"
40
+
41
+ __all__ = [
42
+ "App",
43
+ "Tool",
44
+ "schema_from_function",
45
+ "tool",
46
+ "Context",
47
+ "Runtime",
48
+ "RunContext",
49
+ "Toolbox",
50
+ "__version__",
51
+ ]
52
+
53
+
54
+ def __getattr__(name: str) -> Any:
55
+ if name in {"Context", "RunContext", "Runtime", "Toolbox"}:
56
+ from levier_runtime import Context, RunContext, Runtime
57
+ from levier_runtime.toolbox import Toolbox
58
+
59
+ exports = {
60
+ "Context": Context,
61
+ "RunContext": RunContext,
62
+ "Runtime": Runtime,
63
+ "Toolbox": Toolbox,
64
+ }
65
+ return exports[name]
66
+ raise AttributeError(f"module 'levier' has no attribute {name!r}")
levier/app.py ADDED
@@ -0,0 +1,239 @@
1
+ """The one-import App surface.
2
+
3
+ An App author writes ordinary functions, decorates them with ``@tool``, and
4
+ hands them to ``App``. Credentials, the server address, MCP references, the
5
+ WebSocket lifecycle, CLI flags, reconnects, and tool-call results stay inside
6
+ the SDK.
7
+
8
+ Copyright 2026 The Levier Authors.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import logging
14
+ import sys
15
+ import threading
16
+ from typing import Any, Callable, Iterable, Sequence
17
+
18
+ from levier_app import LevierApp
19
+
20
+ from .tools import Tool, tool as tool_decorator
21
+
22
+
23
+ class App:
24
+ """A small facade over ``LevierApp`` for the common case."""
25
+
26
+ def __init__(
27
+ self,
28
+ tools: Iterable[Tool | Callable[..., Any]] = (),
29
+ *,
30
+ mcp: str | Sequence[str] | None = None,
31
+ runtime: str | None = None,
32
+ credentials: str | None = None,
33
+ server: str | None = None,
34
+ logger: logging.Logger | None = None,
35
+ on_event: Callable[[dict[str, Any]], None] | None = None,
36
+ ) -> None:
37
+ refs = _mcp_refs(mcp)
38
+ self._app = LevierApp.from_credentials(
39
+ credentials,
40
+ server=server,
41
+ logger=logger,
42
+ on_event=on_event,
43
+ mcp_refs=refs,
44
+ )
45
+ self.runtime = runtime or _default_runtime()
46
+ self.logger = self._app.logger
47
+ self._serve_thread: threading.Thread | None = None
48
+ self._tools: list[Tool] = []
49
+ for item in tools:
50
+ self.add(item)
51
+
52
+ @property
53
+ def app_id(self) -> str:
54
+ return self._app.credentials.app_id
55
+
56
+ @property
57
+ def app_name(self) -> str:
58
+ return self._app.credentials.app_name
59
+
60
+ def add(self, item: Tool | Callable[..., Any]) -> Tool:
61
+ """Add a decorated tool, or decorate a plain function on the spot."""
62
+ value = item if isinstance(item, Tool) else tool_decorator(item)
63
+ self._tools.append(value)
64
+ self._app.tool(
65
+ value.name,
66
+ description=value.description,
67
+ schema=dict(value.schema),
68
+ timeout_ms=value.timeout_ms,
69
+ )(value.invoke)
70
+ return value
71
+
72
+ def tool(
73
+ self,
74
+ function: Tool | Callable[..., Any] | str | None = None,
75
+ *,
76
+ name: str | None = None,
77
+ description: str | None = None,
78
+ schema: dict[str, Any] | None = None,
79
+ timeout_ms: int = 10_000,
80
+ ) -> Tool | Callable[[Callable[..., Any]], Tool]:
81
+ """Decorator form of :meth:`add`.
82
+
83
+ Supports ``@app.tool``, ``@app.tool("name")`` and
84
+ ``@app.tool(name="name", description=...)``.
85
+ """
86
+
87
+ def decorate(function: Callable[..., Any], explicit_name: str | None = None) -> Tool:
88
+ value = tool_decorator(
89
+ function,
90
+ name=explicit_name or name,
91
+ description=description,
92
+ schema=schema,
93
+ timeout_ms=timeout_ms,
94
+ )
95
+ assert isinstance(value, Tool)
96
+ return self.add(value)
97
+
98
+ if callable(function):
99
+ return decorate(function)
100
+ if isinstance(function, str):
101
+ return lambda fn: decorate(fn, function)
102
+ if function is not None:
103
+ raise TypeError("app.tool() expects a function, a name, or keyword options")
104
+ return decorate
105
+
106
+ def serve(self) -> int:
107
+ """Connect and serve tool calls until signal or ``app.stop()``."""
108
+ return self._app.run()
109
+
110
+ def stop(self) -> None:
111
+ """Stop a running :meth:`serve` or one-shot :meth:`run`."""
112
+ self._app.stop()
113
+
114
+ def run(
115
+ self,
116
+ prompt: str | None = None,
117
+ *,
118
+ runtime: str | None = None,
119
+ provider: str = "",
120
+ model: str = "",
121
+ max_steps: int = 8,
122
+ run_ms: int = 60_000,
123
+ tool_ms: int = 10_000,
124
+ timeout: float = 300.0,
125
+ print_output: bool = True,
126
+ ) -> int | dict[str, Any]:
127
+ """Serve when called without a prompt; run once when given one.
128
+
129
+ ``app.run("Add 2 and 3")`` starts the App connection in the background,
130
+ submits the Run, waits for the terminal state, prints the final
131
+ assistant message, and closes the connection again.
132
+ """
133
+ if prompt is None:
134
+ return self.serve()
135
+
136
+ self._start_serving()
137
+ try:
138
+ submitted = self._app.submit_run(
139
+ prompt,
140
+ runtime=runtime or self.runtime,
141
+ provider=provider,
142
+ model=model,
143
+ max_steps=max_steps,
144
+ run_ms=run_ms,
145
+ tool_ms=tool_ms,
146
+ )
147
+ result = self._app.wait_run(submitted["run_id"], timeout=timeout)
148
+ final = _final_message(self._app.get_events(submitted["run_id"]))
149
+ if print_output:
150
+ if final:
151
+ print(final)
152
+ elif result.get("status") != "completed":
153
+ print(f"run {result.get('status', 'failed')}", file=sys.stderr)
154
+ if result.get("status") == "completed":
155
+ return result
156
+ return 1
157
+ finally:
158
+ self._stop_serving()
159
+
160
+ def list_model_providers(self) -> list[dict[str, Any]]:
161
+ """Return the model catalog visible to this App."""
162
+ return self._app.list_model_providers()
163
+
164
+ def tools_manifest(self) -> list[dict[str, Any]]:
165
+ """Return the registered tool metadata."""
166
+ return self._app.tools_manifest()
167
+
168
+ def submit_run(self, prompt: str, *, runtime: str | None = None, **options: Any) -> dict[str, Any]:
169
+ """Submit a Run without blocking."""
170
+ return self._app.submit_run(prompt, runtime=runtime or self.runtime, **options)
171
+
172
+ def wait_run(self, run_id: str, *, timeout: float = 300.0) -> dict[str, Any]:
173
+ return self._app.wait_run(run_id, timeout=timeout)
174
+
175
+ def get_run(self, run_id: str) -> dict[str, Any]:
176
+ return self._app.get_run(run_id)
177
+
178
+ def get_events(self, run_id: str) -> list[dict[str, Any]]:
179
+ return self._app.get_events(run_id)
180
+
181
+ def cancel_run(self, run_id: str) -> dict[str, Any]:
182
+ return self._app.cancel_run(run_id)
183
+
184
+ def _start_serving(self) -> None:
185
+ if self._serve_thread is not None and self._serve_thread.is_alive():
186
+ return
187
+
188
+ def serve() -> None:
189
+ try:
190
+ self._app.run(handle_signals=False)
191
+ except Exception: # the caller already owns the failure path
192
+ self.logger.exception("app connection stopped")
193
+
194
+ self._serve_thread = threading.Thread(target=serve, name="levier-app", daemon=True)
195
+ self._serve_thread.start()
196
+ if not self._app.wait_connected(timeout=15.0):
197
+ self._stop_serving()
198
+ raise RuntimeError("App could not connect to Levier; run `levier status` and retry")
199
+
200
+ def _stop_serving(self) -> None:
201
+ self._app.stop()
202
+ thread = self._serve_thread
203
+ self._serve_thread = None
204
+ if thread is not None:
205
+ thread.join(timeout=5.0)
206
+
207
+
208
+ def _mcp_refs(value: str | Sequence[str] | None) -> list[str] | None:
209
+ if value is None:
210
+ return None
211
+ if isinstance(value, str):
212
+ items = value.split(",")
213
+ else:
214
+ items = list(value)
215
+ refs = [str(item).strip() for item in items if str(item).strip()]
216
+ return refs or None
217
+
218
+
219
+ def _default_runtime() -> str:
220
+ from levier_app.credentials import project_values, profile_values
221
+
222
+ value = project_values().get("runtime", "")
223
+ if isinstance(value, str) and value:
224
+ return value
225
+ return profile_values().get("runtime", "") or "react1"
226
+
227
+
228
+ def _final_message(events: Sequence[dict[str, Any]]) -> str:
229
+ final = ""
230
+ for event in events:
231
+ if event.get("event_type") != "MESSAGE_COMPLETED":
232
+ continue
233
+ content = (event.get("data") or {}).get("content")
234
+ if isinstance(content, str):
235
+ final = content
236
+ return final
237
+
238
+
239
+ __all__ = ["App", "Tool", "tool_decorator"]
levier/tools.py ADDED
@@ -0,0 +1,167 @@
1
+ """Declare ordinary Python functions as Levier tools.
2
+
3
+ The decorator removes the hand-written JSON schema from the App onboarding
4
+ path. Types and defaults are inferred from the function signature; the first
5
+ docstring line becomes the model-facing description.
6
+
7
+ Copyright 2026 The Levier Authors.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import enum
13
+ import inspect
14
+ import types
15
+ import typing
16
+ from dataclasses import dataclass
17
+ from typing import Any, Callable, Mapping, Sequence, Union, get_args, get_origin, get_type_hints
18
+
19
+
20
+ @dataclass(frozen=True)
21
+ class Tool:
22
+ """One callable capability exposed to a model."""
23
+
24
+ name: str
25
+ handler: Callable[..., Any]
26
+ description: str
27
+ schema: Mapping[str, Any]
28
+ timeout_ms: int = 10_000
29
+
30
+ def invoke(self, arguments: Mapping[str, Any] | None = None) -> Any:
31
+ """Call the handler with validated keyword arguments."""
32
+ values = dict(arguments or {})
33
+ return self.handler(**values)
34
+
35
+ def __call__(self, **arguments: Any) -> Any:
36
+ """Call the handler directly, for example ``counter_add(delta=2)``."""
37
+ return self.handler(**arguments)
38
+
39
+
40
+ def tool(
41
+ function: Callable[..., Any] | str | None = None,
42
+ *,
43
+ name: str | None = None,
44
+ description: str | None = None,
45
+ schema: Mapping[str, Any] | None = None,
46
+ timeout_ms: int = 10_000,
47
+ ) -> Tool | Callable[[Callable[..., Any]], Tool]:
48
+ """Turn a function into a ``Tool``.
49
+
50
+ All of these are equivalent::
51
+
52
+ @tool
53
+ def counter_add(delta: int) -> dict: ...
54
+
55
+ @tool()
56
+ def counter_add(delta: int) -> dict: ...
57
+
58
+ @tool("counter_add")
59
+ def add(delta: int) -> dict: ...
60
+ """
61
+
62
+ def decorate(function: Callable[..., Any], explicit_name: str | None = None) -> Tool:
63
+ tool_name = (explicit_name or name or function.__name__).strip()
64
+ if not tool_name:
65
+ raise ValueError("tool name is required")
66
+ if timeout_ms <= 0:
67
+ raise ValueError("tool timeout_ms must be positive")
68
+ return Tool(
69
+ name=tool_name,
70
+ handler=function,
71
+ description=(description or _description(function)).strip(),
72
+ schema=dict(schema) if schema is not None else schema_from_function(function),
73
+ timeout_ms=timeout_ms,
74
+ )
75
+
76
+ if callable(function):
77
+ return decorate(function)
78
+ if isinstance(function, str):
79
+ return lambda fn: decorate(fn, function)
80
+ if function is not None:
81
+ raise TypeError("tool() expects a function, a name, or keyword options")
82
+ return decorate
83
+
84
+
85
+ def schema_from_function(function: Callable[..., Any]) -> dict[str, Any]:
86
+ """Build a small JSON Schema from one function signature."""
87
+ signature = inspect.signature(function)
88
+ try:
89
+ hints = get_type_hints(function)
90
+ except (NameError, TypeError):
91
+ hints = {}
92
+
93
+ properties: dict[str, Any] = {}
94
+ required: list[str] = []
95
+ for parameter in signature.parameters.values():
96
+ if parameter.kind in (parameter.VAR_POSITIONAL, parameter.VAR_KEYWORD):
97
+ continue
98
+ if parameter.name in {"self", "cls"}:
99
+ continue
100
+ annotation = hints.get(parameter.name, parameter.annotation)
101
+ field = _json_schema(annotation)
102
+ if parameter.default is inspect.Parameter.empty:
103
+ required.append(parameter.name)
104
+ elif _json_value(parameter.default):
105
+ field["default"] = parameter.default
106
+ properties[parameter.name] = field
107
+
108
+ schema: dict[str, Any] = {
109
+ "type": "object",
110
+ "properties": properties,
111
+ "additionalProperties": False,
112
+ }
113
+ if required:
114
+ schema["required"] = required
115
+ return schema
116
+
117
+
118
+ def _description(function: Callable[..., Any]) -> str:
119
+ doc = inspect.getdoc(function) or ""
120
+ return doc.splitlines()[0].strip() if doc.splitlines() else ""
121
+
122
+
123
+ def _json_schema(annotation: Any) -> dict[str, Any]:
124
+ if annotation is inspect.Parameter.empty or annotation is Any:
125
+ return {}
126
+ origin = get_origin(annotation)
127
+ if origin is Union or origin is types.UnionType:
128
+ options = [item for item in get_args(annotation) if item is not type(None)]
129
+ if len(options) == 1:
130
+ return _json_schema(options[0])
131
+ return {"anyOf": [_json_schema(item) for item in options]}
132
+ if origin is typing.Annotated:
133
+ return _json_schema(get_args(annotation)[0])
134
+ if origin is typing.Literal:
135
+ values = list(get_args(annotation))
136
+ return {"enum": values}
137
+ if origin in (list, Sequence, typing.Sequence, tuple, set, frozenset):
138
+ args = get_args(annotation)
139
+ result: dict[str, Any] = {"type": "array"}
140
+ if args:
141
+ result["items"] = _json_schema(args[0])
142
+ return result
143
+ if origin in (dict, Mapping, typing.Mapping):
144
+ result = {"type": "object"}
145
+ args = get_args(annotation)
146
+ if len(args) == 2 and args[1] is not Any:
147
+ result["additionalProperties"] = _json_schema(args[1])
148
+ return result
149
+
150
+ if isinstance(annotation, type) and issubclass(annotation, enum.Enum):
151
+ return {"type": "string", "enum": [item.value for item in annotation]}
152
+ mapping = {
153
+ str: {"type": "string"},
154
+ int: {"type": "integer"},
155
+ float: {"type": "number"},
156
+ bool: {"type": "boolean"},
157
+ dict: {"type": "object"},
158
+ list: {"type": "array"},
159
+ }
160
+ return dict(mapping.get(annotation, {}))
161
+
162
+
163
+ def _json_value(value: Any) -> bool:
164
+ return isinstance(value, (str, int, float, bool)) or value is None
165
+
166
+
167
+ __all__ = ["Tool", "schema_from_function", "tool"]
@@ -0,0 +1,72 @@
1
+ Metadata-Version: 2.4
2
+ Name: levier
3
+ Version: 0.1.0
4
+ Summary: The small, friendly Levier Python surface for Apps and Runtimes.
5
+ Requires-Python: >=3.12
6
+ Description-Content-Type: text/markdown
7
+ Requires-Dist: levier-app==0.1.0
8
+ Requires-Dist: levier-runtime==0.1.0
9
+
10
+ # `levier` Python SDK
11
+
12
+ One import for both sides of Levier.
13
+
14
+ ## App
15
+
16
+ ```python
17
+ from levier import App, tool
18
+
19
+ counter = {"value": 0}
20
+
21
+
22
+ @tool
23
+ def counter_add(delta: int) -> dict:
24
+ """Add delta to the counter."""
25
+ counter["value"] += delta
26
+ return {"value": counter["value"]}
27
+
28
+
29
+ app = App(tools=[counter_add], mcp=[])
30
+
31
+ if __name__ == "__main__":
32
+ app.run()
33
+ ```
34
+
35
+ `@tool` infers the JSON schema from type hints and the description from the
36
+ first docstring line. `App` loads credentials, the server address, and MCP refs
37
+ from the user profile, and owns the WebSocket lifecycle.
38
+
39
+ One-shot Run:
40
+
41
+ ```python
42
+ app.run("Add 2, then read the counter.")
43
+ ```
44
+
45
+ ## Runtime
46
+
47
+ ```python
48
+ from levier import Context, Runtime
49
+
50
+
51
+ async def run(ctx: Context) -> str:
52
+ tools = await ctx.toolbox()
53
+ reply = await ctx.chat(ctx.input, tools=tools)
54
+ await ctx.invoke_all(reply, toolbox=tools)
55
+ await ctx.reply(reply.content or "done")
56
+ return "completed"
57
+
58
+
59
+ if __name__ == "__main__":
60
+ Runtime.start(run)
61
+ ```
62
+
63
+ `Runtime.start()` needs no YAML or runtime token for a local `levier up` stack.
64
+ `ctx.toolbox()` includes both local App tools and MCP tools; `ctx.chat()` uses
65
+ the model already resolved for the Run; `ctx.invoke_all()` dispatches each tool
66
+ call to the right source.
67
+
68
+ ## Install from the repository
69
+
70
+ ```sh
71
+ python -m pip install -e ./sdk/python -e ./execution/runtime_sdk -e ./sdk/levier
72
+ ```
@@ -0,0 +1,7 @@
1
+ levier/__init__.py,sha256=HKsRXeaZ69aKQkmHdLpwpdQbXKPRQZ5nwa4oy7nmHvw,1471
2
+ levier/app.py,sha256=LQWxQOJjMX-6c95u5J4q1eNtLouynjZvj72tTyaMelE,7976
3
+ levier/tools.py,sha256=3ivQVHApC0cAKbrv7I9qCj09cef96FaEE1-AV30GQYI,5626
4
+ levier-0.1.0.dist-info/METADATA,sha256=Qi5S2kzc3oPmVnwvTCnFCSCH24YGfI7D0HhGIO1fh6A,1654
5
+ levier-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
6
+ levier-0.1.0.dist-info/top_level.txt,sha256=G2fTrEDL65HPVaRQu68IsqAstOm299mDDH4uZbkkGRk,7
7
+ levier-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ levier