energygraph 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.
@@ -0,0 +1,176 @@
1
+ Metadata-Version: 2.4
2
+ Name: energygraph
3
+ Version: 0.1.0
4
+ Summary: Stateful workflow and agent orchestration for EnergyChain
5
+ Author: EnergyChain
6
+ License-Expression: LicenseRef-Proprietary
7
+ Project-URL: Homepage, https://energychain.app
8
+ Classifier: Intended Audience :: Developers
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Programming Language :: Python :: 3 :: Only
11
+ Classifier: Operating System :: OS Independent
12
+ Requires-Python: >=3.10
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Provides-Extra: energychain
16
+ Requires-Dist: energychain<0.5,>=0.4; extra == "energychain"
17
+ Provides-Extra: dev
18
+ Requires-Dist: pytest>=8; extra == "dev"
19
+ Requires-Dist: build>=1; extra == "dev"
20
+ Requires-Dist: ruff>=0.6; extra == "dev"
21
+ Requires-Dist: playwright==1.56.0; extra == "dev"
22
+ Dynamic: license-file
23
+
24
+ # EnGraph
25
+
26
+ Typed workflows and optional LLM reasoning for applications across energy systems.
27
+ EnGraph is a proprietary framework from [EnergyChain](https://energychain.app).
28
+
29
+ Define the workflow in Python, validate its inputs and transitions, execute it
30
+ locally, and inspect the actual run in Studio. Add individual LLM steps or a
31
+ bounded multi-agent reasoning segment when your application needs them.
32
+
33
+ ## Install
34
+
35
+ Requires Python 3.10 or newer. The release is tested on Python 3.10–3.13.
36
+
37
+ ```bash
38
+ python -m pip install energygraph
39
+ ```
40
+
41
+ The Python import and command-line tool are both named `engraph`. Core execution
42
+ has no third-party runtime dependency and does not require a Cloud account or an
43
+ LLM. To use the optional EnergyChain SDK adapters:
44
+
45
+ ```bash
46
+ python -m pip install "energygraph[energychain]"
47
+ ```
48
+
49
+ ## Create a workflow
50
+
51
+ Save this as `workflow.py`:
52
+
53
+ ```python
54
+ from typing import TypedDict
55
+ from engraph import END, Graph
56
+
57
+
58
+ class Input(TypedDict):
59
+ value: int
60
+
61
+
62
+ class Output(TypedDict):
63
+ doubled: int
64
+
65
+
66
+ class Results(TypedDict, total=False):
67
+ doubled: int
68
+
69
+
70
+ class State(Input, Results):
71
+ pass
72
+
73
+
74
+ def double(inputs, context):
75
+ return {"doubled": inputs["value"] * 2}
76
+
77
+
78
+ graph = (
79
+ Graph("first-workflow", state_type=State, revision="1")
80
+ .add_node("double", double, input_type=Input, output_type=Output)
81
+ .set_entry_point("double")
82
+ .add_edge("double", END)
83
+ .compile()
84
+ )
85
+
86
+ if __name__ == "__main__":
87
+ result = graph.run({"value": 3})
88
+ print(result.status, result.state)
89
+ ```
90
+
91
+ ```bash
92
+ python workflow.py
93
+ engraph dev --app workflow.py:graph
94
+ ```
95
+
96
+ Studio prints its local session URL. Open it and run with `{"value": 3}` to
97
+ inspect the executed nodes and transitions. Studio executes the trusted Python
98
+ file you select; it is a local developer tool. Async applications can use
99
+ `await graph.arun(initial_state)`.
100
+
101
+ ## Add a chosen LLM
102
+
103
+ Use `CallableModel` to wrap an explicitly configured synchronous or asynchronous
104
+ provider client, or `GatewayModel` with the optional EnergyChain `ModelGateway`.
105
+ Your callback receives a `ModelRequest` and returns a JSON object, JSON text or
106
+ `ModelResponse`. EnGraph validates the response against the declared output type.
107
+ No provider or model is chosen automatically.
108
+
109
+ For example, this function accepts your configured model binding and returns a
110
+ typed LLM workflow:
111
+
112
+ ```python
113
+ from typing import TypedDict
114
+ from engraph import END, Graph, LLMNode
115
+
116
+
117
+ class Question(TypedDict):
118
+ question: str
119
+
120
+
121
+ class Answer(TypedDict):
122
+ answer: str
123
+
124
+
125
+ class ResultFields(TypedDict, total=False):
126
+ answer: str
127
+
128
+
129
+ class ReasoningState(Question, ResultFields):
130
+ pass
131
+
132
+
133
+ def build_llm_workflow(model):
134
+ node = LLMNode(
135
+ model,
136
+ instruction="Answer accurately and state uncertainty.",
137
+ input_type=Question,
138
+ output_type=Answer,
139
+ )
140
+ return (
141
+ Graph("chosen-model", state_type=ReasoningState, revision="1")
142
+ .add_node("answer", node.as_node(), input_type=Question, output_type=Answer)
143
+ .set_entry_point("answer")
144
+ .add_edge("answer", END)
145
+ .compile()
146
+ )
147
+ ```
148
+
149
+ Keep provider credentials in your application's secret configuration. A model
150
+ binding does not grant permission to access tools or equipment.
151
+
152
+ ## Multi-agent reasoning
153
+
154
+ `engraph.reasoning.ReasoningSegment` expands configured coordinator, specialist,
155
+ synthesizer and verifier roles into ordinary graph nodes before compilation.
156
+ Configure each role with an `AgentSpec`, register authorized read/analysis tools
157
+ through `ToolBinding`, define a `Problem`, and set finite `ReasoningLimits`.
158
+ Roles can share a selected model or use different models.
159
+
160
+ Tool observations carry source references. Synthesis and verification use the
161
+ recorded evidence; application checks can reject a candidate answer. The final
162
+ `reasoning_result` reports `answered`, `partial`, `needs_input` or `blocked`.
163
+ Inspect both graph execution status and the reasoning outcome.
164
+
165
+ This initial developer release executes sequentially with bounded reasoning
166
+ rounds. Native cyclic or parallel scheduling, durable recovery, hosted execution
167
+ and physical equipment control are not included. Evaluate your chosen model and
168
+ workflow on representative tasks before relying on its answers in production.
169
+
170
+ ## License
171
+
172
+ Proprietary software. Copyright (c) 2026 EnergyChain. All rights reserved.
173
+ The distribution includes its proprietary notice as `LICENSE`.
174
+ Public PyPI distribution does not make EnGraph open source or keep downloaded
175
+ Python code confidential. The EnergyChain SDK remains a separate dependency with
176
+ its own license.
@@ -0,0 +1,25 @@
1
+ energygraph-0.1.0.dist-info/licenses/LICENSE,sha256=HeeOsxKVa_NUtHdrHoJe2_vkW6rXMV4eV5wzB7XZYqs,301
2
+ engraph/__init__.py,sha256=IsWO0v3hBYkH5jZzS1QhoGhTy9DF96R91cb1IaLSXnM,648
3
+ engraph/cli.py,sha256=pFgffFyF9m6btPBubRJqiMumKuYk5-3ENfwU8ihHa6A,2442
4
+ engraph/contracts.py,sha256=O4p1rr-DRHbsMej2slcQHc4FEPsENGfuzNhFGJ2LBNI,1423
5
+ engraph/ensmith_adapter.py,sha256=ze-VLOKV5mIimi-b26hazKH7fnD3-YFAbA3bhprRS4I,5616
6
+ engraph/errors.py,sha256=u6X2qc0wdFzUaNjMUWNoKJ45_c5fHfPTAu3LY3edyQc,409
7
+ engraph/graph.py,sha256=0PCcaCHuWx2C6gJ0MQVwku1lCHMdDP4ym66khA9i88U,16758
8
+ engraph/models.py,sha256=8YTpz3M-z44-1kqb1vG0VDgSaBoxUAaugnAmDvk4z6c,9601
9
+ engraph/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
10
+ engraph/studio.py,sha256=tp73bd_is-xvQQcJ3BNOUtvnPr6VCfAKH4Mu_P56voE,9774
11
+ engraph/tools.py,sha256=IAqOoWa34xjo5D5sWE9xQ3QYPtgLXXo3-6JL78D9irw,2711
12
+ engraph/values.py,sha256=ruabS1V2jHfAM3rWLirCXqMTRMY7eDdm1JzzXqLk7w8,8283
13
+ engraph/reasoning/__init__.py,sha256=xEQn6U4uPglqIcSVx_X11HtLN64bmy1qQtxJ0jlUNhw,561
14
+ engraph/reasoning/contracts.py,sha256=MjGfM_L-ZrtgvaL7sJrl6zglbdyBJ29wHlrJqhOUePk,7508
15
+ engraph/reasoning/schemas.py,sha256=gAGo8-JrIIrJRioI16wu0Pcnwk_XMoJC_Fsn6HpWrNw,1589
16
+ engraph/reasoning/segment.py,sha256=M-0-FhiLPH6SVgYz9Q-QV5rVmqPpOMvE1uC64ds2Z-8,39232
17
+ engraph/reasoning/validation.py,sha256=0vFS-geKHoEsOFQN1Dnp_lRpe0GoRqQqtj3N13Cmx2s,6831
18
+ engraph/studio_assets/app.js,sha256=JFL_B6OxURDiycJVNAJlWwj8iJRuF33jLgzOw2RrUCA,13936
19
+ engraph/studio_assets/index.html,sha256=tKOdX412PdVOAWomX6vcIOHGKzO8lx5Gr-p2PwoekJ8,3203
20
+ engraph/studio_assets/style.css,sha256=gnIO8zsItAtVBq4rZR9RLVqfYzkTW01XIKLra0CFluE,6719
21
+ energygraph-0.1.0.dist-info/METADATA,sha256=xo3GSS7GiPZu9FoQpO7VU4aMmgHoTct7kouqGy1uupI,5400
22
+ energygraph-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
23
+ energygraph-0.1.0.dist-info/entry_points.txt,sha256=nNVdI4nCwA1M7LOdyNfbHHs8nNI5qXZm4S8qi7LKLTE,45
24
+ energygraph-0.1.0.dist-info/top_level.txt,sha256=ZbHURBbWrpBWTasIlsWM2vYwsFbQhCgmOMMDIQfDxFk,8
25
+ energygraph-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,2 @@
1
+ [console_scripts]
2
+ engraph = engraph.cli:main
@@ -0,0 +1,8 @@
1
+ EnGraph — Proprietary software
2
+
3
+ Copyright (c) 2026 EnergyChain. All rights reserved.
4
+
5
+ EnGraph is not licensed under an open-source license.
6
+
7
+ Distribution through the Python Package Index is subject to the applicable PyPI
8
+ Terms of Service. No additional license or rights are granted by this notice.
@@ -0,0 +1 @@
1
+ engraph
engraph/__init__.py ADDED
@@ -0,0 +1,25 @@
1
+ """Typed local workflows with optional provider-neutral LLM reasoning."""
2
+
3
+ from .contracts import END, CancellationToken, NodeContext, RunResult
4
+ from .graph import CompiledGraph, Graph
5
+ from .ensmith_adapter import export_ensmith_spans
6
+ from .tools import EnergyChainTool
7
+ from .models import CallableModel, GatewayModel, LLMNode, ModelRequest, ModelResponse
8
+
9
+ __version__ = "0.1.0"
10
+ __all__ = [
11
+ "END",
12
+ "CancellationToken",
13
+ "CompiledGraph",
14
+ "EnergyChainTool",
15
+ "Graph",
16
+ "export_ensmith_spans",
17
+ "NodeContext",
18
+ "RunResult",
19
+ "CallableModel",
20
+ "GatewayModel",
21
+ "LLMNode",
22
+ "ModelRequest",
23
+ "ModelResponse",
24
+ ]
25
+
engraph/cli.py ADDED
@@ -0,0 +1,62 @@
1
+ """Load only explicitly trusted local Python. No remote code or browser upload."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import importlib.util
7
+ import sys
8
+ import webbrowser
9
+ from pathlib import Path
10
+
11
+ from .graph import CompiledGraph, Graph
12
+ from .studio import StudioServer
13
+
14
+
15
+ def load_app(value):
16
+ path_text, separator, name = value.rpartition(":")
17
+ if not separator or not name.isidentifier():
18
+ raise ValueError("use --app trusted_file.py:graph")
19
+ path = Path(path_text).resolve(strict=True)
20
+ if path.suffix != ".py":
21
+ raise ValueError("app must be a trusted local Python file")
22
+ spec = importlib.util.spec_from_file_location("_engraph_trusted_app", path)
23
+ module = importlib.util.module_from_spec(spec)
24
+ # Required for dataclasses and postponed annotations in trusted application modules.
25
+ sys.modules[spec.name] = module
26
+ spec.loader.exec_module(module)
27
+ app = getattr(module, name)
28
+ if isinstance(app, Graph):
29
+ app = app.compile()
30
+ if isinstance(app, CompiledGraph):
31
+ return app
32
+ if isinstance(app, dict) and all(isinstance(g, CompiledGraph) for g in app.values()):
33
+ return app
34
+ raise ValueError("app must export a Graph, CompiledGraph or mapping of compiled graphs")
35
+
36
+
37
+ def main(argv=None):
38
+ parser = argparse.ArgumentParser(prog="engraph", description="EnGraph local developer tools")
39
+ commands = parser.add_subparsers(dest="command", required=True)
40
+ dev = commands.add_parser("dev", help="inspect trusted local graphs in Studio")
41
+ dev.add_argument("--app", required=True, help="trusted_file.py:graph (executes local Python)")
42
+ dev.add_argument("--host", default="127.0.0.1", choices=("127.0.0.1", "localhost"))
43
+ dev.add_argument("--port", type=int, default=8765)
44
+ dev.add_argument("--no-browser", action="store_true")
45
+ args = parser.parse_args(argv)
46
+ if not 0 <= args.port <= 65535:
47
+ parser.error("port must be from 0 to 65535")
48
+ server = StudioServer(load_app(args.app), host=args.host, port=args.port)
49
+ print("EnGraph Studio · trusted local execution · Ctrl+C to stop", flush=True)
50
+ print(server.url, flush=True) # Token in fragment, never an HTTP query or access log.
51
+ if not args.no_browser:
52
+ webbrowser.open(server.url)
53
+ try:
54
+ server.serve_forever()
55
+ except KeyboardInterrupt:
56
+ pass
57
+ finally:
58
+ server.server_close()
59
+
60
+
61
+ if __name__ == "__main__":
62
+ main()
engraph/contracts.py ADDED
@@ -0,0 +1,60 @@
1
+ """Versioned local runtime contracts. No provider, Cloud or EnSmith dependency."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import threading
6
+ from dataclasses import asdict, dataclass, field
7
+ from datetime import datetime, timezone
8
+ from typing import Any
9
+
10
+ from .values import json_copy
11
+
12
+ END = "__end__"
13
+ GRAPH_SCHEMA = "engraph.graph.v1"
14
+ EVENT_SCHEMA = "engraph.event.v1"
15
+ RESULT_SCHEMA = "engraph.result.v1"
16
+
17
+
18
+ def timestamp() -> str:
19
+ return datetime.now(timezone.utc).isoformat()
20
+
21
+
22
+ class CancellationToken:
23
+ """Trusted host cancellation, observed at node boundaries; no hard interruption."""
24
+
25
+ def __init__(self):
26
+ self._event = threading.Event()
27
+
28
+ def cancel(self) -> None:
29
+ self._event.set()
30
+
31
+ @property
32
+ def cancelled(self) -> bool:
33
+ return self._event.is_set()
34
+
35
+
36
+ @dataclass(frozen=True)
37
+ class NodeContext:
38
+ run_id: str
39
+ graph_id: str
40
+ graph_version: str
41
+ node_id: str
42
+ step: int
43
+
44
+
45
+ @dataclass
46
+ class RunResult:
47
+ run_id: str
48
+ graph_id: str
49
+ graph_version: str
50
+ state: dict[str, Any]
51
+ status: str = "running"
52
+ steps: int = 0
53
+ failed_node: str | None = None
54
+ error_type: str | None = None
55
+ events: list[dict] = field(default_factory=list)
56
+ schema_version: str = RESULT_SCHEMA
57
+
58
+ def to_dict(self) -> dict:
59
+ """Host-local result including state; Studio uses metadata/events only."""
60
+ return json_copy(asdict(self), max_bytes=None)
@@ -0,0 +1,139 @@
1
+ """INC-ENG-002: explicit, metadata-only EnSmith span export from real EnGraph runs.
2
+
3
+ No EnSmith or Cloud import, API key, background network call, or implicit tracing.
4
+ This experimental v0 adapter never exports state, payloads, or exception text.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import hashlib
9
+ import math
10
+ import re
11
+ import uuid
12
+ from datetime import datetime
13
+ from typing import Any
14
+
15
+ from .contracts import EVENT_SCHEMA, RESULT_SCHEMA, RunResult
16
+
17
+ SPAN_SCHEMA = "ensmith.span.v0"
18
+ _HEX_ID = re.compile(r"[0-9a-f]{32}\Z")
19
+ _NAME = re.compile(r"[A-Za-z][A-Za-z0-9_.-]{0,79}\Z")
20
+ _SUPPORTED = frozenset({"completed", "failed", "cancelled"})
21
+
22
+
23
+ def _span_id(run_id: str, event: str) -> str:
24
+ return uuid.uuid5(uuid.NAMESPACE_URL, "engraph/" + run_id + "/" + event).hex
25
+
26
+
27
+ def _stamp(value: Any) -> str:
28
+ if not isinstance(value, str):
29
+ raise ValueError("event timestamp must be timezone-aware")
30
+ try:
31
+ dt = datetime.fromisoformat(value)
32
+ except ValueError as exc:
33
+ raise ValueError("invalid event timestamp") from exc
34
+ if dt.tzinfo is None or dt.utcoffset() is None:
35
+ raise ValueError("event timestamp must be timezone-aware")
36
+ return value
37
+
38
+
39
+ def _duration(value: Any) -> float | None:
40
+ if type(value) not in (int, float):
41
+ return None
42
+ try:
43
+ f = float(value)
44
+ except (OverflowError, ValueError):
45
+ return None
46
+ return f if math.isfinite(f) and f >= 0 else None
47
+
48
+
49
+ def export_ensmith_spans(result: RunResult, *, max_spans: int = 1000) -> list[dict]:
50
+ """Convert one *completed* EnGraph RunResult to EnSmith v0 span dictionaries.
51
+
52
+ The export is stable across retries for a given run ID and event sequence.
53
+ It never uploads. A caller must separately authorize hosted ingestion.
54
+ """
55
+ if not isinstance(result, RunResult) or result.schema_version != RESULT_SCHEMA:
56
+ raise ValueError("expected a versioned EnGraph RunResult")
57
+ if result.status not in _SUPPORTED:
58
+ raise ValueError("only terminal EnGraph runs are exportable")
59
+ if type(max_spans) is not int or not 1 <= max_spans <= 10_000:
60
+ raise ValueError("invalid span budget")
61
+ if not isinstance(result.run_id, str) or not 1 <= len(result.run_id) <= 128:
62
+ raise ValueError("invalid run ID")
63
+ if not isinstance(result.graph_id, str) or not _NAME.fullmatch(result.graph_id):
64
+ raise ValueError("invalid graph ID")
65
+ if not isinstance(result.events, list) or not result.events:
66
+ raise ValueError("missing execution events")
67
+ run_id = result.run_id
68
+ trace_id = (
69
+ run_id if _HEX_ID.fullmatch(run_id)
70
+ else hashlib.sha256(("engraph:" + run_id).encode()).hexdigest()[:32]
71
+ )
72
+ root_id = _span_id(run_id, "root")
73
+ records: list[dict] = []
74
+
75
+ def span(span_id: str, parent: str | None, operation: str, source: str,
76
+ outcome: str, timestamp: str, duration_ms: float | None) -> dict:
77
+ return {
78
+ "schema_version": SPAN_SCHEMA,
79
+ "trace_id": trace_id,
80
+ "span_id": span_id,
81
+ "parent_span_id": parent,
82
+ "operation": operation,
83
+ "source": source,
84
+ "outcome": outcome,
85
+ "timestamp": timestamp,
86
+ "duration_ms": duration_ms,
87
+ "provider": None,
88
+ "model": None,
89
+ "input_tokens": None,
90
+ "output_tokens": None,
91
+ "total_tokens": None,
92
+ }
93
+
94
+ for i, event in enumerate(result.events, start=1):
95
+ if (
96
+ not isinstance(event, dict)
97
+ or event.get("schema_version") != EVENT_SCHEMA
98
+ or event.get("run_id") != run_id
99
+ or event.get("graph_id") != result.graph_id
100
+ or event.get("graph_version") != result.graph_version
101
+ or event.get("sequence") != i
102
+ ):
103
+ raise ValueError("inconsistent EnGraph execution event")
104
+ stamp = _stamp(event.get("timestamp"))
105
+ kind = event.get("type")
106
+ if kind in ("node_completed", "node_failed"):
107
+ node_id = event.get("node_id")
108
+ if not isinstance(node_id, str) or not _NAME.fullmatch(node_id):
109
+ raise ValueError("invalid node identity")
110
+ metadata = event.get("metadata")
111
+ duration = _duration(metadata.get("duration_ms")) if isinstance(metadata, dict) else None
112
+ records.append(
113
+ span(
114
+ _span_id(run_id, "node:" + str(i)), root_id,
115
+ "node." + node_id, "engraph.node",
116
+ "success" if kind == "node_completed" else "failed",
117
+ stamp, duration if kind == "node_completed" else None,
118
+ )
119
+ )
120
+ if len(records) + 1 > max_spans:
121
+ raise ValueError("span budget exceeded")
122
+
123
+ terminal_kind = {
124
+ "completed": "run_completed",
125
+ "failed": "run_failed",
126
+ "cancelled": "run_cancelled",
127
+ }[result.status]
128
+ if result.events[-1].get("type") != terminal_kind:
129
+ raise ValueError("terminal run status does not match execution events")
130
+
131
+ # Cancellation is not silently reported as success or failed execution.
132
+ # EnSmith v0 lacks a dedicated cancelled status: encode it explicitly in source.
133
+ root_source = "engraph.run.cancelled" if result.status == "cancelled" else "engraph.run"
134
+ root_status = {"completed": "success", "failed": "failed", "cancelled": "unknown"}[result.status]
135
+ root = span(
136
+ root_id, None, "graph." + result.graph_id, root_source,
137
+ root_status, _stamp(result.events[0].get("timestamp")), None,
138
+ )
139
+ return [root, *records]
engraph/errors.py ADDED
@@ -0,0 +1,25 @@
1
+ """Content-free error classes; exception messages are never captured by the runtime."""
2
+
3
+
4
+ class EnGraphError(Exception):
5
+ pass
6
+
7
+
8
+ class GraphValidationError(EnGraphError, ValueError):
9
+ pass
10
+
11
+
12
+ class StateValidationError(EnGraphError, ValueError):
13
+ pass
14
+
15
+
16
+ class BudgetExceeded(EnGraphError):
17
+ pass
18
+
19
+
20
+ class RouteValidationError(EnGraphError):
21
+ pass
22
+
23
+
24
+ class ToolAccessDenied(EnGraphError):
25
+ pass