kegal 0.1.4.0__tar.gz

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.
Files changed (56) hide show
  1. kegal-0.1.4.0/LICENSE +21 -0
  2. kegal-0.1.4.0/PKG-INFO +306 -0
  3. kegal-0.1.4.0/README.md +252 -0
  4. kegal-0.1.4.0/kegal/__init__.py +94 -0
  5. kegal-0.1.4.0/kegal/cli.py +185 -0
  6. kegal-0.1.4.0/kegal/compiler.py +1761 -0
  7. kegal-0.1.4.0/kegal/compose.py +108 -0
  8. kegal-0.1.4.0/kegal/graph.py +90 -0
  9. kegal-0.1.4.0/kegal/graph_blackboard.py +37 -0
  10. kegal-0.1.4.0/kegal/graph_edge.py +24 -0
  11. kegal-0.1.4.0/kegal/graph_history.py +6 -0
  12. kegal-0.1.4.0/kegal/graph_mcp.py +32 -0
  13. kegal-0.1.4.0/kegal/graph_model.py +20 -0
  14. kegal-0.1.4.0/kegal/graph_node.py +70 -0
  15. kegal-0.1.4.0/kegal/graph_react.py +7 -0
  16. kegal-0.1.4.0/kegal/llm/__init__.py +25 -0
  17. kegal-0.1.4.0/kegal/llm/llm_anthropic.py +293 -0
  18. kegal-0.1.4.0/kegal/llm/llm_bedrock.py +244 -0
  19. kegal-0.1.4.0/kegal/llm/llm_gemini.py +206 -0
  20. kegal-0.1.4.0/kegal/llm/llm_handler.py +39 -0
  21. kegal-0.1.4.0/kegal/llm/llm_model.py +273 -0
  22. kegal-0.1.4.0/kegal/llm/llm_ollama.py +184 -0
  23. kegal-0.1.4.0/kegal/llm/llm_openai.py +191 -0
  24. kegal-0.1.4.0/kegal/mcp_handler.py +179 -0
  25. kegal-0.1.4.0/kegal/utils.py +258 -0
  26. kegal-0.1.4.0/kegal/validators.py +321 -0
  27. kegal-0.1.4.0/kegal.egg-info/PKG-INFO +306 -0
  28. kegal-0.1.4.0/kegal.egg-info/SOURCES.txt +54 -0
  29. kegal-0.1.4.0/kegal.egg-info/dependency_links.txt +1 -0
  30. kegal-0.1.4.0/kegal.egg-info/entry_points.txt +2 -0
  31. kegal-0.1.4.0/kegal.egg-info/requires.txt +29 -0
  32. kegal-0.1.4.0/kegal.egg-info/top_level.txt +1 -0
  33. kegal-0.1.4.0/pyproject.toml +3 -0
  34. kegal-0.1.4.0/setup.cfg +4 -0
  35. kegal-0.1.4.0/setup.py +52 -0
  36. kegal-0.1.4.0/test/test_blackboard.py +616 -0
  37. kegal-0.1.4.0/test/test_bug_fixes.py +540 -0
  38. kegal-0.1.4.0/test/test_chat_history.py +604 -0
  39. kegal-0.1.4.0/test/test_cli.py +227 -0
  40. kegal-0.1.4.0/test/test_graphs.py +661 -0
  41. kegal-0.1.4.0/test/test_history_field.py +78 -0
  42. kegal-0.1.4.0/test/test_llm.py +170 -0
  43. kegal-0.1.4.0/test/test_llm_anthropic.py +78 -0
  44. kegal-0.1.4.0/test/test_llm_bedrock.py +53 -0
  45. kegal-0.1.4.0/test/test_llm_bedrock_unit.py +78 -0
  46. kegal-0.1.4.0/test/test_llm_gemini.py +46 -0
  47. kegal-0.1.4.0/test/test_llm_gemini_unit.py +257 -0
  48. kegal-0.1.4.0/test/test_llm_ollama.py +32 -0
  49. kegal-0.1.4.0/test/test_llm_openai.py +35 -0
  50. kegal-0.1.4.0/test/test_mcp_sqlite.py +43 -0
  51. kegal-0.1.4.0/test/test_mcp_sqlite_chain.py +46 -0
  52. kegal-0.1.4.0/test/test_node_features.py +439 -0
  53. kegal-0.1.4.0/test/test_ordered_edges.py +471 -0
  54. kegal-0.1.4.0/test/test_react.py +1233 -0
  55. kegal-0.1.4.0/test/test_react_research.py +400 -0
  56. kegal-0.1.4.0/test/test_validators.py +104 -0
kegal-0.1.4.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Kedos srl
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
kegal-0.1.4.0/PKG-INFO ADDED
@@ -0,0 +1,306 @@
1
+ Metadata-Version: 2.4
2
+ Name: kegal
3
+ Version: 0.1.4.0
4
+ Summary: KeGAL - Kedos Graph Agent for LLM
5
+ Home-page: https://github.com/kedos-srl/kegal
6
+ Author: Kedos srl
7
+ Author-email: fabio.gagliardi@kedos-srl.it
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
17
+ Requires-Python: >=3.10
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Requires-Dist: pydantic>=2.0.0
21
+ Requires-Dist: PyYAML>=6.0
22
+ Requires-Dist: jsonschema>=4.20.0
23
+ Requires-Dist: PyMuPDF>=1.24.0
24
+ Requires-Dist: mcp>=1.0.0
25
+ Provides-Extra: anthropic
26
+ Requires-Dist: anthropic>=0.25.0; extra == "anthropic"
27
+ Provides-Extra: openai
28
+ Requires-Dist: openai>=1.0.0; extra == "openai"
29
+ Provides-Extra: ollama
30
+ Requires-Dist: ollama>=0.2.0; extra == "ollama"
31
+ Provides-Extra: aws
32
+ Requires-Dist: boto3>=1.34.0; extra == "aws"
33
+ Requires-Dist: botocore>=1.34.0; extra == "aws"
34
+ Provides-Extra: gemini
35
+ Requires-Dist: google-genai>=1.0.0; extra == "gemini"
36
+ Provides-Extra: all
37
+ Requires-Dist: anthropic>=0.25.0; extra == "all"
38
+ Requires-Dist: boto3>=1.34.0; extra == "all"
39
+ Requires-Dist: botocore>=1.34.0; extra == "all"
40
+ Requires-Dist: google-genai>=1.0.0; extra == "all"
41
+ Requires-Dist: ollama>=0.2.0; extra == "all"
42
+ Requires-Dist: openai>=1.0.0; extra == "all"
43
+ Dynamic: author
44
+ Dynamic: author-email
45
+ Dynamic: classifier
46
+ Dynamic: description
47
+ Dynamic: description-content-type
48
+ Dynamic: home-page
49
+ Dynamic: license-file
50
+ Dynamic: provides-extra
51
+ Dynamic: requires-dist
52
+ Dynamic: requires-python
53
+ Dynamic: summary
54
+
55
+ # KeGAL - Kedos Graph Agent for LLM
56
+
57
+ KeGAL is a graph-based agent framework for LLMs. It enables the development
58
+ of workflows structured as graphs, where each node represents an agent,
59
+ and input and output messages are formatted as structured JSON files.
60
+
61
+ An agent can be designed using prompt engineering for specific tasks.
62
+ Additionally, each agent can utilize tools written in Python to connect to
63
+ external knowledge sources. Moreover, agents can invoke external services via HTTP,
64
+ allowing seamless integration with various systems.
65
+
66
+ The core concept of KeGAL is to leverage one or more LLMs to manage workflow
67
+ execution within the architecture. Agents contain no traditional code; instead,
68
+ everything is controlled by the LLM through its tooling capabilities.
69
+
70
+ ## Installation
71
+
72
+ Install directly from GitHub:
73
+
74
+ ```bash
75
+ pip install git+https://github.com/kedos-srl/kegal.git
76
+ ```
77
+
78
+ From `requirements.txt`:
79
+ ```
80
+ kegal @ git+https://github.com/kedos-srl/kegal.git
81
+ ```
82
+
83
+ Or clone and install in development mode:
84
+
85
+ ```bash
86
+ git clone https://github.com/kedos-srl/kegal.git
87
+ cd kegal
88
+ pip install -r requirements.txt
89
+ pip install -e .
90
+ ```
91
+
92
+ ## Documentation
93
+
94
+ - [Graph Framework](docs/graph_doc.md) - Full field reference for the `Graph` model hierarchy
95
+ - [LLM Providers](docs/llm_doc.md) - Guide on LLM providers and integration
96
+ - [Tutorials](docs/tutorials.md) - 13 topic tutorials from basics to advanced: structured output, RAG, chat history, blackboard, ReAct, and more
97
+ - [Changelog](docs/CHANGELOG.md) - Version history and release notes
98
+
99
+ ## Quick Start
100
+
101
+ ### Basic usage
102
+
103
+ ```python
104
+ from kegal import Compiler
105
+
106
+ compiler = Compiler(uri="path/to/your_graph.yml")
107
+ compiler.compile()
108
+ outputs = compiler.get_outputs()
109
+ ```
110
+
111
+ Always release the compiler when you are done. It frees:
112
+ - **MCP servers** — stopped and their background threads joined (only if the graph uses MCP)
113
+ - **LLM clients** — HTTP connection pools closed (only if the provider exposes `close()`)
114
+
115
+ Without it, sockets may remain open until the garbage collector finalises the object,
116
+ producing `ResourceWarning` noise in tests and connection leaks in long-running services.
117
+
118
+ The recommended pattern is the `with` statement — `close()` is called automatically
119
+ on exit, even if `compile()` raises:
120
+
121
+ ```python
122
+ with Compiler(uri="path/to/your_graph.yml") as compiler:
123
+ compiler.compile()
124
+ outputs = compiler.get_outputs()
125
+ ```
126
+
127
+ In `unittest`, use `setUp` / `tearDown`:
128
+
129
+ ```python
130
+ class TestMyGraph(unittest.TestCase):
131
+ def setUp(self):
132
+ self.compiler = Compiler(uri="path/to/your_graph.yml")
133
+
134
+ def tearDown(self):
135
+ self.compiler.close()
136
+
137
+ def test_compile(self):
138
+ self.compiler.compile()
139
+ outputs = self.compiler.get_outputs()
140
+ ...
141
+ ```
142
+
143
+ ### Inspecting outputs
144
+
145
+ `get_outputs()` returns a `CompiledOutput` object:
146
+
147
+ ```python
148
+ outputs = compiler.get_outputs()
149
+
150
+ for node in outputs.nodes:
151
+ print(f"[{node.node_id}]")
152
+ if node.response.messages:
153
+ for msg in node.response.messages: # LLM text response (list of strings)
154
+ print(msg)
155
+ if node.response.json_output:
156
+ print(node.response.json_output) # structured JSON output
157
+ print(node.compiled_time) # seconds this node took
158
+ if node.context_window: # context utilization (when context_window is set)
159
+ pct = node.response.input_size / node.context_window * 100
160
+ print(f"context: {node.response.input_size}/{node.context_window} ({pct:.1f}%)")
161
+
162
+ print(f"total time : {outputs.compile_time:.2f}s")
163
+ print(f"input tokens : {outputs.input_size}")
164
+ print(f"output tokens: {outputs.output_size}")
165
+ ```
166
+
167
+ All executed nodes are included in `outputs.nodes`. The `show` flag on a node
168
+ is a display hint used by `save_outputs_as_markdown()`; it does not filter
169
+ what is returned by `get_outputs()`.
170
+
171
+ ### Overriding the user message at runtime
172
+
173
+ The `user_message` defined in the YAML is the default. You can replace it before
174
+ calling `compile()` to drive the same graph with different inputs:
175
+
176
+ ```python
177
+ with Compiler(uri="path/to/your_graph.yml") as compiler:
178
+ compiler.user_message = "Explain the risks of nuclear energy."
179
+ compiler.compile()
180
+ ```
181
+
182
+ ### Defining tools in Python
183
+
184
+ `LLMTool` and `LLMStructuredSchema` are available at the top of the import tree:
185
+
186
+ ```python
187
+ from kegal import LLMTool
188
+ from kegal.llm import LLMStructuredSchema
189
+ ```
190
+
191
+ ### Loading from a dict
192
+
193
+ If the graph is built programmatically rather than read from a file, pass a
194
+ `source` dict instead of a URI:
195
+
196
+ ```python
197
+ graph_dict = {
198
+ "models": [{"llm": "ollama", "model": "ministral-3:3b", "host": "http://localhost:11434"}],
199
+ "user_message": "Hello",
200
+ "prompts": [...],
201
+ "nodes": [...],
202
+ "edges": [...],
203
+ }
204
+ with Compiler(source=graph_dict) as compiler:
205
+ compiler.compile()
206
+ ```
207
+
208
+ For more advanced usage — attaching Python tool executors, MCP servers, fan-out/fan-in
209
+ pipelines, guard nodes, RAG, and multi-provider graphs — see [docs/tutorials.md](docs/tutorials.md).
210
+
211
+ ## CLI
212
+
213
+ After installation, the `kegal` command is available in your shell.
214
+
215
+ ```bash
216
+ kegal --version # print installed version
217
+ kegal run [path] # run a project
218
+ ```
219
+
220
+ ### Project layout
221
+
222
+ A KeGAL project is a folder containing a mandatory `kegal.yml` config file and your graph definition:
223
+
224
+ ```
225
+ my_project/
226
+ ├── kegal.yml
227
+ └── my_graph.yml
228
+ ```
229
+
230
+ `kegal.yml` fields:
231
+
232
+ | Field | Required | Values | Description |
233
+ |-------|----------|--------|-------------|
234
+ | `graph` | yes | path | Path to the graph YAML/JSON, relative to `kegal.yml` |
235
+ | `mode` | no | `once` (default), `chat` | Execution mode |
236
+ | `message` | no | `true`/`false` | Prompt for `user_message` each turn — chat mode only |
237
+ | `chunks` | no | `true`/`false` | Prompt for RAG chunks each turn — chat mode only |
238
+
239
+ Unknown keys in `kegal.yml` are warned and ignored. Setting `message`/`chunks` with `mode: once` also warns.
240
+
241
+ **`once` mode** — runs the graph once using values from the YAML and exits:
242
+
243
+ ```yaml
244
+ # kegal.yml
245
+ graph: my_graph.yml
246
+ mode: once
247
+ ```
248
+
249
+ **`chat` mode** — keeps a loop alive; prompts for user input on every turn until `Ctrl+D`:
250
+
251
+ ```yaml
252
+ # kegal.yml
253
+ graph: my_graph.yml
254
+ mode: chat
255
+ message: true
256
+ chunks: false
257
+ ```
258
+
259
+ Configuration and runtime errors print a clean `Error: …` message and exit with code 1. In chat mode, per-turn errors print the message and continue the loop.
260
+
261
+ ### Running a project
262
+
263
+ ```bash
264
+ # from inside the project folder
265
+ kegal run
266
+
267
+ # or specify the path
268
+ kegal run path/to/my_project
269
+ ```
270
+
271
+ ## Features
272
+
273
+ - **Graph-based workflows** – define multi-node agent pipelines in YAML or JSON
274
+ - **Fan-out / fan-in edges** – `children` launches parallel sub-tasks; `fan_in` aggregates multiple branches before continuing; both are recursive and composable
275
+ - **Multi-board blackboard pipeline** – multiple named shared markdown boards (`GraphBlackboard`) written and read across nodes; Cat-1 writers seed a board, Cat-2 enrichers extend it in parallel, Cat-3 readers consume the final result. Boards support `import` chains (prepend another board's content at read time) and `cleanup` control (truncate at init or preserve existing content). Execution order is inferred automatically from `blackboard.read/write` flags even with flat edge declarations.
276
+ - **ReAct loop** – controller node iteratively reasons and dispatches to specialist agent nodes until it signals `done: true`; supports automatic conversation compaction (`resume: true`) for long loops; controller output flows to downstream nodes via `message_passing` like any regular node
277
+ - **Structured output** – enforce JSON schemas on LLM responses
278
+ - **Validation gate** – nodes with a `validation` boolean field in their structured output act as guards: when the LLM returns `validation: false`, the graph execution stops immediately, preventing downstream nodes from running. Useful for content moderation and prompt injection prevention.
279
+ - **Message passing** – forward node outputs to downstream nodes; ordering inferred automatically from flags and declaration order — no explicit edge required for linear pipelines
280
+ - **Verbose logging** – set `verbose: true` on the graph to get a colored INFO-level trace on stderr: compile start/done with token totals, per-node start/end with elapsed time and token counts, each tool call (`[mcp]`/`[py]` tagged) with parameters and result preview, and the full ReAct loop trace. ANSI colors are applied automatically on TTY terminals and suppressed on pipes/redirects
281
+ - **MCP support** – connect nodes to external tool servers via the Model Context Protocol (stdio and SSE transports)
282
+ - **Python tool executors** – attach plain Python callables as tools without running a separate process
283
+ - **Multi-provider support** – use different LLMs in the same graph
284
+ - **Context window tracking** – declare `context_window` on a model to get accurate `resume` compaction thresholds and per-node context-utilization percentages in markdown output
285
+ - **Chat history** – maintain conversational context across nodes; scopes can be inline arrays or external JSON files with optional `auto: true` to let KeGAL append user+assistant turns automatically after each `compile()` call
286
+ - **RAG support** – inject retrieved document chunks into prompts
287
+ - **Prompt validation** – at `Compiler()` construction, placeholder tokens in every prompt template are checked against the node config; misconfigurations are reported as warnings before the first `compile()` call
288
+ - **Safe resource cleanup** – `compiler.close()` releases MCP server processes and LLM HTTP connection pools; idempotent and transport-aware
289
+
290
+ ## Supported LLM Providers
291
+
292
+ - **Anthropic** - Direct API and AWS Bedrock
293
+ - **OpenAI** - GPT models
294
+ - **Ollama** - Local LLM hosting
295
+ - **AWS Bedrock** - Amazon Nova and other models
296
+
297
+
298
+ ## TO DO
299
+ - Add support for gemini
300
+
301
+
302
+ ## Copyright
303
+
304
+ Copyright 2025 by [Kedos srl](https://www.kedos-srl.it/).
305
+
306
+ This software is released under the [MIT](LICENSE) license.
@@ -0,0 +1,252 @@
1
+ # KeGAL - Kedos Graph Agent for LLM
2
+
3
+ KeGAL is a graph-based agent framework for LLMs. It enables the development
4
+ of workflows structured as graphs, where each node represents an agent,
5
+ and input and output messages are formatted as structured JSON files.
6
+
7
+ An agent can be designed using prompt engineering for specific tasks.
8
+ Additionally, each agent can utilize tools written in Python to connect to
9
+ external knowledge sources. Moreover, agents can invoke external services via HTTP,
10
+ allowing seamless integration with various systems.
11
+
12
+ The core concept of KeGAL is to leverage one or more LLMs to manage workflow
13
+ execution within the architecture. Agents contain no traditional code; instead,
14
+ everything is controlled by the LLM through its tooling capabilities.
15
+
16
+ ## Installation
17
+
18
+ Install directly from GitHub:
19
+
20
+ ```bash
21
+ pip install git+https://github.com/kedos-srl/kegal.git
22
+ ```
23
+
24
+ From `requirements.txt`:
25
+ ```
26
+ kegal @ git+https://github.com/kedos-srl/kegal.git
27
+ ```
28
+
29
+ Or clone and install in development mode:
30
+
31
+ ```bash
32
+ git clone https://github.com/kedos-srl/kegal.git
33
+ cd kegal
34
+ pip install -r requirements.txt
35
+ pip install -e .
36
+ ```
37
+
38
+ ## Documentation
39
+
40
+ - [Graph Framework](docs/graph_doc.md) - Full field reference for the `Graph` model hierarchy
41
+ - [LLM Providers](docs/llm_doc.md) - Guide on LLM providers and integration
42
+ - [Tutorials](docs/tutorials.md) - 13 topic tutorials from basics to advanced: structured output, RAG, chat history, blackboard, ReAct, and more
43
+ - [Changelog](docs/CHANGELOG.md) - Version history and release notes
44
+
45
+ ## Quick Start
46
+
47
+ ### Basic usage
48
+
49
+ ```python
50
+ from kegal import Compiler
51
+
52
+ compiler = Compiler(uri="path/to/your_graph.yml")
53
+ compiler.compile()
54
+ outputs = compiler.get_outputs()
55
+ ```
56
+
57
+ Always release the compiler when you are done. It frees:
58
+ - **MCP servers** — stopped and their background threads joined (only if the graph uses MCP)
59
+ - **LLM clients** — HTTP connection pools closed (only if the provider exposes `close()`)
60
+
61
+ Without it, sockets may remain open until the garbage collector finalises the object,
62
+ producing `ResourceWarning` noise in tests and connection leaks in long-running services.
63
+
64
+ The recommended pattern is the `with` statement — `close()` is called automatically
65
+ on exit, even if `compile()` raises:
66
+
67
+ ```python
68
+ with Compiler(uri="path/to/your_graph.yml") as compiler:
69
+ compiler.compile()
70
+ outputs = compiler.get_outputs()
71
+ ```
72
+
73
+ In `unittest`, use `setUp` / `tearDown`:
74
+
75
+ ```python
76
+ class TestMyGraph(unittest.TestCase):
77
+ def setUp(self):
78
+ self.compiler = Compiler(uri="path/to/your_graph.yml")
79
+
80
+ def tearDown(self):
81
+ self.compiler.close()
82
+
83
+ def test_compile(self):
84
+ self.compiler.compile()
85
+ outputs = self.compiler.get_outputs()
86
+ ...
87
+ ```
88
+
89
+ ### Inspecting outputs
90
+
91
+ `get_outputs()` returns a `CompiledOutput` object:
92
+
93
+ ```python
94
+ outputs = compiler.get_outputs()
95
+
96
+ for node in outputs.nodes:
97
+ print(f"[{node.node_id}]")
98
+ if node.response.messages:
99
+ for msg in node.response.messages: # LLM text response (list of strings)
100
+ print(msg)
101
+ if node.response.json_output:
102
+ print(node.response.json_output) # structured JSON output
103
+ print(node.compiled_time) # seconds this node took
104
+ if node.context_window: # context utilization (when context_window is set)
105
+ pct = node.response.input_size / node.context_window * 100
106
+ print(f"context: {node.response.input_size}/{node.context_window} ({pct:.1f}%)")
107
+
108
+ print(f"total time : {outputs.compile_time:.2f}s")
109
+ print(f"input tokens : {outputs.input_size}")
110
+ print(f"output tokens: {outputs.output_size}")
111
+ ```
112
+
113
+ All executed nodes are included in `outputs.nodes`. The `show` flag on a node
114
+ is a display hint used by `save_outputs_as_markdown()`; it does not filter
115
+ what is returned by `get_outputs()`.
116
+
117
+ ### Overriding the user message at runtime
118
+
119
+ The `user_message` defined in the YAML is the default. You can replace it before
120
+ calling `compile()` to drive the same graph with different inputs:
121
+
122
+ ```python
123
+ with Compiler(uri="path/to/your_graph.yml") as compiler:
124
+ compiler.user_message = "Explain the risks of nuclear energy."
125
+ compiler.compile()
126
+ ```
127
+
128
+ ### Defining tools in Python
129
+
130
+ `LLMTool` and `LLMStructuredSchema` are available at the top of the import tree:
131
+
132
+ ```python
133
+ from kegal import LLMTool
134
+ from kegal.llm import LLMStructuredSchema
135
+ ```
136
+
137
+ ### Loading from a dict
138
+
139
+ If the graph is built programmatically rather than read from a file, pass a
140
+ `source` dict instead of a URI:
141
+
142
+ ```python
143
+ graph_dict = {
144
+ "models": [{"llm": "ollama", "model": "ministral-3:3b", "host": "http://localhost:11434"}],
145
+ "user_message": "Hello",
146
+ "prompts": [...],
147
+ "nodes": [...],
148
+ "edges": [...],
149
+ }
150
+ with Compiler(source=graph_dict) as compiler:
151
+ compiler.compile()
152
+ ```
153
+
154
+ For more advanced usage — attaching Python tool executors, MCP servers, fan-out/fan-in
155
+ pipelines, guard nodes, RAG, and multi-provider graphs — see [docs/tutorials.md](docs/tutorials.md).
156
+
157
+ ## CLI
158
+
159
+ After installation, the `kegal` command is available in your shell.
160
+
161
+ ```bash
162
+ kegal --version # print installed version
163
+ kegal run [path] # run a project
164
+ ```
165
+
166
+ ### Project layout
167
+
168
+ A KeGAL project is a folder containing a mandatory `kegal.yml` config file and your graph definition:
169
+
170
+ ```
171
+ my_project/
172
+ ├── kegal.yml
173
+ └── my_graph.yml
174
+ ```
175
+
176
+ `kegal.yml` fields:
177
+
178
+ | Field | Required | Values | Description |
179
+ |-------|----------|--------|-------------|
180
+ | `graph` | yes | path | Path to the graph YAML/JSON, relative to `kegal.yml` |
181
+ | `mode` | no | `once` (default), `chat` | Execution mode |
182
+ | `message` | no | `true`/`false` | Prompt for `user_message` each turn — chat mode only |
183
+ | `chunks` | no | `true`/`false` | Prompt for RAG chunks each turn — chat mode only |
184
+
185
+ Unknown keys in `kegal.yml` are warned and ignored. Setting `message`/`chunks` with `mode: once` also warns.
186
+
187
+ **`once` mode** — runs the graph once using values from the YAML and exits:
188
+
189
+ ```yaml
190
+ # kegal.yml
191
+ graph: my_graph.yml
192
+ mode: once
193
+ ```
194
+
195
+ **`chat` mode** — keeps a loop alive; prompts for user input on every turn until `Ctrl+D`:
196
+
197
+ ```yaml
198
+ # kegal.yml
199
+ graph: my_graph.yml
200
+ mode: chat
201
+ message: true
202
+ chunks: false
203
+ ```
204
+
205
+ Configuration and runtime errors print a clean `Error: …` message and exit with code 1. In chat mode, per-turn errors print the message and continue the loop.
206
+
207
+ ### Running a project
208
+
209
+ ```bash
210
+ # from inside the project folder
211
+ kegal run
212
+
213
+ # or specify the path
214
+ kegal run path/to/my_project
215
+ ```
216
+
217
+ ## Features
218
+
219
+ - **Graph-based workflows** – define multi-node agent pipelines in YAML or JSON
220
+ - **Fan-out / fan-in edges** – `children` launches parallel sub-tasks; `fan_in` aggregates multiple branches before continuing; both are recursive and composable
221
+ - **Multi-board blackboard pipeline** – multiple named shared markdown boards (`GraphBlackboard`) written and read across nodes; Cat-1 writers seed a board, Cat-2 enrichers extend it in parallel, Cat-3 readers consume the final result. Boards support `import` chains (prepend another board's content at read time) and `cleanup` control (truncate at init or preserve existing content). Execution order is inferred automatically from `blackboard.read/write` flags even with flat edge declarations.
222
+ - **ReAct loop** – controller node iteratively reasons and dispatches to specialist agent nodes until it signals `done: true`; supports automatic conversation compaction (`resume: true`) for long loops; controller output flows to downstream nodes via `message_passing` like any regular node
223
+ - **Structured output** – enforce JSON schemas on LLM responses
224
+ - **Validation gate** – nodes with a `validation` boolean field in their structured output act as guards: when the LLM returns `validation: false`, the graph execution stops immediately, preventing downstream nodes from running. Useful for content moderation and prompt injection prevention.
225
+ - **Message passing** – forward node outputs to downstream nodes; ordering inferred automatically from flags and declaration order — no explicit edge required for linear pipelines
226
+ - **Verbose logging** – set `verbose: true` on the graph to get a colored INFO-level trace on stderr: compile start/done with token totals, per-node start/end with elapsed time and token counts, each tool call (`[mcp]`/`[py]` tagged) with parameters and result preview, and the full ReAct loop trace. ANSI colors are applied automatically on TTY terminals and suppressed on pipes/redirects
227
+ - **MCP support** – connect nodes to external tool servers via the Model Context Protocol (stdio and SSE transports)
228
+ - **Python tool executors** – attach plain Python callables as tools without running a separate process
229
+ - **Multi-provider support** – use different LLMs in the same graph
230
+ - **Context window tracking** – declare `context_window` on a model to get accurate `resume` compaction thresholds and per-node context-utilization percentages in markdown output
231
+ - **Chat history** – maintain conversational context across nodes; scopes can be inline arrays or external JSON files with optional `auto: true` to let KeGAL append user+assistant turns automatically after each `compile()` call
232
+ - **RAG support** – inject retrieved document chunks into prompts
233
+ - **Prompt validation** – at `Compiler()` construction, placeholder tokens in every prompt template are checked against the node config; misconfigurations are reported as warnings before the first `compile()` call
234
+ - **Safe resource cleanup** – `compiler.close()` releases MCP server processes and LLM HTTP connection pools; idempotent and transport-aware
235
+
236
+ ## Supported LLM Providers
237
+
238
+ - **Anthropic** - Direct API and AWS Bedrock
239
+ - **OpenAI** - GPT models
240
+ - **Ollama** - Local LLM hosting
241
+ - **AWS Bedrock** - Amazon Nova and other models
242
+
243
+
244
+ ## TO DO
245
+ - Add support for gemini
246
+
247
+
248
+ ## Copyright
249
+
250
+ Copyright 2025 by [Kedos srl](https://www.kedos-srl.it/).
251
+
252
+ This software is released under the [MIT](LICENSE) license.
@@ -0,0 +1,94 @@
1
+ """
2
+ KeGAL - Kedos Graph Agent for LLM
3
+
4
+ A graph-based agent framework for LLMs that enables the development
5
+ of workflows structured as graphs.
6
+ """
7
+
8
+ from .graph import (
9
+ Graph,
10
+ GraphModel,
11
+ GraphInputData,
12
+ GraphBlackboard,
13
+ BlackboardEntry,
14
+ NodeBlackboardRef,
15
+ ChatHistoryFile,
16
+ NodePrompt,
17
+ NodeMessagePassing,
18
+ NodeMcpServerRef,
19
+ NodeReact,
20
+ GraphNode,
21
+ GraphEdge,
22
+ GraphMcpServer,
23
+ )
24
+ from .compiler import Compiler, CompiledOutput, CompiledNodeOutput, ReactTrace, ReactIteration
25
+ from .compose import (
26
+ compose_template_prompt,
27
+ compose_node_prompt,
28
+ compose_images,
29
+ compose_documents,
30
+ compose_tools,
31
+ )
32
+ from .utils import (
33
+ load_yml,
34
+ load_json,
35
+ load_contents,
36
+ load_images_to_base64,
37
+ load_pdfs_to_base64,
38
+ )
39
+ from .validators import (
40
+ validate_anthropic_schema,
41
+ validate_openai_schema,
42
+ validate_llm_input_schema,
43
+ SchemaIssue,
44
+ )
45
+
46
+ # Import LLM subpackage
47
+ from . import llm
48
+ from .llm.llm_model import LLMTool
49
+
50
+ __version__ = "0.1.4.0"
51
+
52
+ __all__ = [
53
+ # Graph models
54
+ "Graph",
55
+ "GraphModel",
56
+ "GraphInputData",
57
+ "GraphBlackboard",
58
+ "BlackboardEntry",
59
+ "NodeBlackboardRef",
60
+ "ChatHistoryFile",
61
+ "NodePrompt",
62
+ "NodeMessagePassing",
63
+ "NodeMcpServerRef",
64
+ "NodeReact",
65
+ "GraphNode",
66
+ "GraphEdge",
67
+ "GraphMcpServer",
68
+ # Compiler
69
+ "Compiler",
70
+ "CompiledOutput",
71
+ "CompiledNodeOutput",
72
+ "ReactTrace",
73
+ "ReactIteration",
74
+ # Compose utilities
75
+ "compose_template_prompt",
76
+ "compose_node_prompt",
77
+ "compose_images",
78
+ "compose_documents",
79
+ "compose_tools",
80
+ # Utils
81
+ "load_yml",
82
+ "load_json",
83
+ "load_contents",
84
+ "load_images_to_base64",
85
+ "load_pdfs_to_base64",
86
+ # Validators
87
+ "validate_anthropic_schema",
88
+ "validate_openai_schema",
89
+ "validate_llm_input_schema",
90
+ "SchemaIssue",
91
+ # LLM subpackage
92
+ "llm",
93
+ "LLMTool",
94
+ ]