runtime-narrative 0.1.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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Shashank Raj
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.
@@ -0,0 +1,195 @@
1
+ Metadata-Version: 2.4
2
+ Name: runtime-narrative
3
+ Version: 0.1.0
4
+ Summary: runtime-narrative — model execution as human-readable stories
5
+ Author-email: Shashank Raj <shashank.raj28@gmail.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/sraj0501/runtime_narrative
8
+ Project-URL: Repository, https://github.com/sraj0501/runtime_narrative
9
+ Project-URL: Bug Tracker, https://github.com/sraj0501/runtime_narrative/issues
10
+ Keywords: logging,observability,tracing,fastapi,debugging,runtime_narrative
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.9
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
21
+ Classifier: Topic :: System :: Logging
22
+ Classifier: Topic :: System :: Monitoring
23
+ Classifier: Typing :: Typed
24
+ Requires-Python: >=3.9
25
+ Description-Content-Type: text/markdown
26
+ License-File: LICENSE
27
+ Provides-Extra: console
28
+ Requires-Dist: typer>=0.9.0; extra == "console"
29
+ Provides-Extra: fastapi
30
+ Requires-Dist: starlette>=0.27.0; extra == "fastapi"
31
+ Provides-Extra: all
32
+ Requires-Dist: typer>=0.9.0; extra == "all"
33
+ Requires-Dist: starlette>=0.27.0; extra == "all"
34
+ Dynamic: license-file
35
+
36
+ # runtime_narrative
37
+
38
+ Model your application's execution as **human-readable stories** instead of scattered log lines.
39
+
40
+ When something fails, instead of a raw traceback you get:
41
+
42
+ ```
43
+ ❌ Failure detected
44
+ Story: Create Customer
45
+ Stage: Validate Input
46
+ Error: ValueError - invalid email
47
+ Location: handlers.py:24 (validate_customer)
48
+ Code: if "@" not in payload.email:
49
+ Progress: 33% (1 / 3 stages completed)
50
+ Recent stages: Validate Input=failed (0.001s)
51
+ ```
52
+
53
+ ## Installation
54
+
55
+ ```bash
56
+ # Core only (zero dependencies)
57
+ pip install runtime-narrative
58
+
59
+ # With colored console output
60
+ pip install "runtime-narrative[console]"
61
+
62
+ # With FastAPI middleware
63
+ pip install "runtime-narrative[fastapi]"
64
+
65
+ # Everything
66
+ pip install "runtime-narrative[all]"
67
+ ```
68
+
69
+ ## Quick start
70
+
71
+ ```python
72
+ from runtime_narrative import story, stage
73
+
74
+ with story("Import Customers"):
75
+ with stage("Load CSV"):
76
+ load_file()
77
+
78
+ with stage("Validate Data"):
79
+ validate()
80
+
81
+ with stage("Insert Records"):
82
+ insert()
83
+ ```
84
+
85
+ ## FastAPI — middleware (recommended)
86
+
87
+ Add middleware once and every request gets a story automatically.
88
+ Route handlers only need to declare stages:
89
+
90
+ ```python
91
+ from runtime_narrative import RuntimeNarrativeMiddleware, stage
92
+
93
+ app.add_middleware(RuntimeNarrativeMiddleware)
94
+
95
+ @app.post("/customers")
96
+ async def create_customer(payload: CustomerIn):
97
+ with stage("Validate Input"):
98
+ ...
99
+ with stage("Insert Into Database"):
100
+ ...
101
+ with stage("Build Response"):
102
+ return {"ok": True}
103
+ ```
104
+
105
+ ## FastAPI — decorator style
106
+
107
+ ```python
108
+ from runtime_narrative import runtime_narrative_story, runtime_narrative_stage
109
+
110
+ @app.post("/customers")
111
+ @runtime_narrative_story("Create Customer")
112
+ async def create_customer(payload: CustomerIn):
113
+ return await _save(payload)
114
+
115
+ @runtime_narrative_stage("Save to Database")
116
+ async def _save(payload):
117
+ ...
118
+ ```
119
+
120
+ ## Structured JSON output
121
+
122
+ Pipe one JSON object per lifecycle event to stdout, a file, or any stream:
123
+
124
+ ```python
125
+ from runtime_narrative import RuntimeNarrativeMiddleware, JsonRenderer
126
+
127
+ app.add_middleware(RuntimeNarrativeMiddleware, renderers=[JsonRenderer()])
128
+ ```
129
+
130
+ Output (one line per event):
131
+ ```json
132
+ {"event": "StoryStarted", "story_id": "...", "story_name": "POST /customers", "timestamp": "..."}
133
+ {"event": "StageStarted", "story_id": "...", "stage_name": "Validate Input", "timestamp": "..."}
134
+ {"event": "StageCompleted", "story_id": "...", "stage_name": "Validate Input", "duration_seconds": 0.001, "timestamp": "..."}
135
+ {"event": "StoryCompleted", "story_id": "...", "success": true, "progress": {"percent": 100, ...}, "timestamp": "..."}
136
+ ```
137
+
138
+ Write to a file instead of stdout:
139
+
140
+ ```python
141
+ JsonRenderer(output=open("runtime_narrative.log", "a"))
142
+ ```
143
+
144
+ ## LLM failure analysis
145
+
146
+ Plug in any LLM backend — model name and endpoint are always required (no defaults).
147
+
148
+ **OpenAI-compatible backends** (vLLM, llama.cpp `--server`, LM Studio, Ollama OpenAI mode):
149
+
150
+ ```python
151
+ from runtime_narrative import LLMFailureAnalyzer, story
152
+
153
+ analyzer = LLMFailureAnalyzer(
154
+ model="llama3",
155
+ endpoint="http://localhost:8000/v1/chat/completions",
156
+ )
157
+
158
+ with story("Process Orders", failure_analyzer=analyzer):
159
+ ...
160
+ ```
161
+
162
+ **Ollama native API:**
163
+
164
+ ```python
165
+ from runtime_narrative import OllamaFailureAnalyzer, story
166
+
167
+ analyzer = OllamaFailureAnalyzer(
168
+ model="llama3",
169
+ endpoint="http://localhost:11434/api/generate",
170
+ )
171
+
172
+ with story("Process Orders", failure_analyzer=analyzer):
173
+ ...
174
+ ```
175
+
176
+ Falls back silently if the endpoint is unavailable.
177
+
178
+ ## Custom renderer
179
+
180
+ Implement a single `handle` method to receive all lifecycle events:
181
+
182
+ ```python
183
+ class MyRenderer:
184
+ def handle(self, event):
185
+ print(event.__class__.__name__, event.__dict__)
186
+
187
+ with story("My Story", renderers=[MyRenderer()]):
188
+ ...
189
+ ```
190
+
191
+ Events: `StoryStarted`, `StageStarted`, `StageCompleted`, `FailureOccurred`, `StoryCompleted`.
192
+
193
+ ## License
194
+
195
+ MIT
@@ -0,0 +1,160 @@
1
+ # runtime_narrative
2
+
3
+ Model your application's execution as **human-readable stories** instead of scattered log lines.
4
+
5
+ When something fails, instead of a raw traceback you get:
6
+
7
+ ```
8
+ ❌ Failure detected
9
+ Story: Create Customer
10
+ Stage: Validate Input
11
+ Error: ValueError - invalid email
12
+ Location: handlers.py:24 (validate_customer)
13
+ Code: if "@" not in payload.email:
14
+ Progress: 33% (1 / 3 stages completed)
15
+ Recent stages: Validate Input=failed (0.001s)
16
+ ```
17
+
18
+ ## Installation
19
+
20
+ ```bash
21
+ # Core only (zero dependencies)
22
+ pip install runtime-narrative
23
+
24
+ # With colored console output
25
+ pip install "runtime-narrative[console]"
26
+
27
+ # With FastAPI middleware
28
+ pip install "runtime-narrative[fastapi]"
29
+
30
+ # Everything
31
+ pip install "runtime-narrative[all]"
32
+ ```
33
+
34
+ ## Quick start
35
+
36
+ ```python
37
+ from runtime_narrative import story, stage
38
+
39
+ with story("Import Customers"):
40
+ with stage("Load CSV"):
41
+ load_file()
42
+
43
+ with stage("Validate Data"):
44
+ validate()
45
+
46
+ with stage("Insert Records"):
47
+ insert()
48
+ ```
49
+
50
+ ## FastAPI — middleware (recommended)
51
+
52
+ Add middleware once and every request gets a story automatically.
53
+ Route handlers only need to declare stages:
54
+
55
+ ```python
56
+ from runtime_narrative import RuntimeNarrativeMiddleware, stage
57
+
58
+ app.add_middleware(RuntimeNarrativeMiddleware)
59
+
60
+ @app.post("/customers")
61
+ async def create_customer(payload: CustomerIn):
62
+ with stage("Validate Input"):
63
+ ...
64
+ with stage("Insert Into Database"):
65
+ ...
66
+ with stage("Build Response"):
67
+ return {"ok": True}
68
+ ```
69
+
70
+ ## FastAPI — decorator style
71
+
72
+ ```python
73
+ from runtime_narrative import runtime_narrative_story, runtime_narrative_stage
74
+
75
+ @app.post("/customers")
76
+ @runtime_narrative_story("Create Customer")
77
+ async def create_customer(payload: CustomerIn):
78
+ return await _save(payload)
79
+
80
+ @runtime_narrative_stage("Save to Database")
81
+ async def _save(payload):
82
+ ...
83
+ ```
84
+
85
+ ## Structured JSON output
86
+
87
+ Pipe one JSON object per lifecycle event to stdout, a file, or any stream:
88
+
89
+ ```python
90
+ from runtime_narrative import RuntimeNarrativeMiddleware, JsonRenderer
91
+
92
+ app.add_middleware(RuntimeNarrativeMiddleware, renderers=[JsonRenderer()])
93
+ ```
94
+
95
+ Output (one line per event):
96
+ ```json
97
+ {"event": "StoryStarted", "story_id": "...", "story_name": "POST /customers", "timestamp": "..."}
98
+ {"event": "StageStarted", "story_id": "...", "stage_name": "Validate Input", "timestamp": "..."}
99
+ {"event": "StageCompleted", "story_id": "...", "stage_name": "Validate Input", "duration_seconds": 0.001, "timestamp": "..."}
100
+ {"event": "StoryCompleted", "story_id": "...", "success": true, "progress": {"percent": 100, ...}, "timestamp": "..."}
101
+ ```
102
+
103
+ Write to a file instead of stdout:
104
+
105
+ ```python
106
+ JsonRenderer(output=open("runtime_narrative.log", "a"))
107
+ ```
108
+
109
+ ## LLM failure analysis
110
+
111
+ Plug in any LLM backend — model name and endpoint are always required (no defaults).
112
+
113
+ **OpenAI-compatible backends** (vLLM, llama.cpp `--server`, LM Studio, Ollama OpenAI mode):
114
+
115
+ ```python
116
+ from runtime_narrative import LLMFailureAnalyzer, story
117
+
118
+ analyzer = LLMFailureAnalyzer(
119
+ model="llama3",
120
+ endpoint="http://localhost:8000/v1/chat/completions",
121
+ )
122
+
123
+ with story("Process Orders", failure_analyzer=analyzer):
124
+ ...
125
+ ```
126
+
127
+ **Ollama native API:**
128
+
129
+ ```python
130
+ from runtime_narrative import OllamaFailureAnalyzer, story
131
+
132
+ analyzer = OllamaFailureAnalyzer(
133
+ model="llama3",
134
+ endpoint="http://localhost:11434/api/generate",
135
+ )
136
+
137
+ with story("Process Orders", failure_analyzer=analyzer):
138
+ ...
139
+ ```
140
+
141
+ Falls back silently if the endpoint is unavailable.
142
+
143
+ ## Custom renderer
144
+
145
+ Implement a single `handle` method to receive all lifecycle events:
146
+
147
+ ```python
148
+ class MyRenderer:
149
+ def handle(self, event):
150
+ print(event.__class__.__name__, event.__dict__)
151
+
152
+ with story("My Story", renderers=[MyRenderer()]):
153
+ ...
154
+ ```
155
+
156
+ Events: `StoryStarted`, `StageStarted`, `StageCompleted`, `FailureOccurred`, `StoryCompleted`.
157
+
158
+ ## License
159
+
160
+ MIT
@@ -0,0 +1,58 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "runtime-narrative"
7
+ version = "0.1.0"
8
+ description = "runtime-narrative — model execution as human-readable stories"
9
+ readme = "README.MD"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.9"
13
+ # TODO: replace with your real name and email before publishing
14
+ authors = [
15
+ { name = "Shashank Raj", email = "shashank.raj28@gmail.com" },
16
+ ]
17
+ keywords = ["logging", "observability", "tracing", "fastapi", "debugging", "runtime_narrative"]
18
+ classifiers = [
19
+ "Development Status :: 4 - Beta",
20
+ "Intended Audience :: Developers",
21
+ "Operating System :: OS Independent",
22
+ "Programming Language :: Python :: 3",
23
+ "Programming Language :: Python :: 3.9",
24
+ "Programming Language :: Python :: 3.10",
25
+ "Programming Language :: Python :: 3.11",
26
+ "Programming Language :: Python :: 3.12",
27
+ "Programming Language :: Python :: 3.13",
28
+ "Topic :: Software Development :: Libraries :: Python Modules",
29
+ "Topic :: System :: Logging",
30
+ "Topic :: System :: Monitoring",
31
+ "Typing :: Typed",
32
+ ]
33
+ dependencies = []
34
+
35
+ [project.optional-dependencies]
36
+ # Colored terminal output via typer
37
+ console = ["typer>=0.9.0"]
38
+ # FastAPI / Starlette middleware
39
+ fastapi = ["starlette>=0.27.0"]
40
+ # Install everything
41
+ all = [
42
+ "typer>=0.9.0",
43
+ "starlette>=0.27.0",
44
+ ]
45
+
46
+ [project.urls]
47
+ Homepage = "https://github.com/sraj0501/runtime_narrative"
48
+ Repository = "https://github.com/sraj0501/runtime_narrative"
49
+ "Bug Tracker" = "https://github.com/sraj0501/runtime_narrative/issues"
50
+
51
+ [tool.setuptools]
52
+ packages = ["runtime_narrative", "runtime_narrative.renderer", "runtime_narrative.analyzers"]
53
+
54
+ [dependency-groups]
55
+ dev = [
56
+ "build>=1.4.0",
57
+ "twine>=6.2.0",
58
+ ]
@@ -0,0 +1,23 @@
1
+ __version__ = "0.1.0"
2
+
3
+ from .analyzers import LLMFailureAnalyzer, OllamaFailureAnalyzer
4
+ from .decorators import runtime_narrative_stage, runtime_narrative_story
5
+ from .renderer.json_renderer import JsonRenderer
6
+ from .stage import stage
7
+ from .story import story
8
+
9
+ try:
10
+ from .middleware import RuntimeNarrativeMiddleware
11
+ except ImportError:
12
+ pass
13
+
14
+ __all__ = [
15
+ "story",
16
+ "stage",
17
+ "runtime_narrative_story",
18
+ "runtime_narrative_stage",
19
+ "LLMFailureAnalyzer",
20
+ "OllamaFailureAnalyzer",
21
+ "RuntimeNarrativeMiddleware",
22
+ "JsonRenderer",
23
+ ]
@@ -0,0 +1,3 @@
1
+ from .ollama import LLMFailureAnalyzer, OllamaFailureAnalyzer
2
+
3
+ __all__ = ["LLMFailureAnalyzer", "OllamaFailureAnalyzer"]
@@ -0,0 +1,179 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from dataclasses import dataclass, field
5
+ from typing import Optional
6
+ from urllib.error import URLError
7
+ from urllib.request import Request, urlopen
8
+
9
+ from ..failure import FailureSummary
10
+
11
+
12
+ def _build_prompt(
13
+ *,
14
+ story_name: str,
15
+ stage_name: str,
16
+ failure: FailureSummary,
17
+ stage_timeline: str,
18
+ progress_percent: int,
19
+ include_traceback_lines: int,
20
+ ) -> str:
21
+ traceback_lines = failure.traceback_text.strip().splitlines()
22
+ traceback_excerpt = "\n".join(traceback_lines[-include_traceback_lines:])
23
+ return (
24
+ "You are debugging a Python runtime stage failure.\n"
25
+ "Return concise markdown with exactly four sections:\n"
26
+ "1) Exact Why\n"
27
+ "2) Evidence\n"
28
+ "3) Targeted Fix\n\n"
29
+ "4) Code Changes\n\n"
30
+ "Constraints:\n"
31
+ "- Do not be generic.\n"
32
+ "- Point to the exact failing statement and mechanism.\n"
33
+ "- Mention assumptions only if uncertain.\n\n"
34
+ "Code Changes format:\n"
35
+ "- Provide minimal edit-ready snippets.\n"
36
+ "- Include file path, old line, and new line when possible.\n"
37
+ "- Prefer small targeted diffs over full-file rewrites.\n\n"
38
+ f"Story: {story_name}\n"
39
+ f"Stage: {stage_name}\n"
40
+ f"Error Type: {failure.error_type}\n"
41
+ f"Error Message: {failure.error_message}\n"
42
+ f"Location: {failure.filename}:{failure.lineno} ({failure.function})\n"
43
+ f"Failing Code: {failure.source_line}\n"
44
+ f"Exception Chain: {failure.exception_chain}\n"
45
+ f"Progress: {progress_percent}%\n"
46
+ f"Recent Stages: {stage_timeline}\n\n"
47
+ "Traceback Excerpt:\n"
48
+ f"{traceback_excerpt}\n"
49
+ )
50
+
51
+
52
+ @dataclass
53
+ class LLMFailureAnalyzer:
54
+ """
55
+ Failure analyzer for OpenAI-compatible endpoints.
56
+
57
+ Works with any backend that serves the /v1/chat/completions API,
58
+ including vLLM, llama.cpp (--server), LM Studio, Ollama (OpenAI mode), etc.
59
+
60
+ Example::
61
+
62
+ LLMFailureAnalyzer(
63
+ model="llama3",
64
+ endpoint="http://localhost:8000/v1/chat/completions",
65
+ )
66
+ """
67
+
68
+ model: str
69
+ endpoint: str
70
+ timeout_seconds: float = 12.0
71
+ include_traceback_lines: int = 30
72
+
73
+ def analyze_failure(
74
+ self,
75
+ *,
76
+ story_name: str,
77
+ stage_name: str,
78
+ failure: FailureSummary,
79
+ stage_timeline: str,
80
+ progress_percent: int,
81
+ ) -> Optional[str]:
82
+ prompt = _build_prompt(
83
+ story_name=story_name,
84
+ stage_name=stage_name,
85
+ failure=failure,
86
+ stage_timeline=stage_timeline,
87
+ progress_percent=progress_percent,
88
+ include_traceback_lines=self.include_traceback_lines,
89
+ )
90
+ payload = {
91
+ "model": self.model,
92
+ "messages": [{"role": "user", "content": prompt}],
93
+ "temperature": 0,
94
+ "stream": False,
95
+ }
96
+ request = Request(
97
+ self.endpoint,
98
+ data=json.dumps(payload).encode("utf-8"),
99
+ headers={"Content-Type": "application/json"},
100
+ method="POST",
101
+ )
102
+ try:
103
+ with urlopen(request, timeout=self.timeout_seconds) as response:
104
+ body = response.read().decode("utf-8")
105
+ except (URLError, TimeoutError, Exception):
106
+ return None
107
+
108
+ try:
109
+ parsed = json.loads(body)
110
+ text = parsed["choices"][0]["message"]["content"].strip()
111
+ except Exception:
112
+ return None
113
+
114
+ return text or None
115
+
116
+
117
+ @dataclass
118
+ class OllamaFailureAnalyzer:
119
+ """
120
+ Failure analyzer using Ollama's native /api/generate endpoint.
121
+
122
+ For OpenAI-compatible mode (Ollama >= 0.1.24), prefer LLMFailureAnalyzer
123
+ with endpoint="http://localhost:11434/v1/chat/completions".
124
+
125
+ Example::
126
+
127
+ OllamaFailureAnalyzer(
128
+ model="llama3",
129
+ endpoint="http://localhost:11434/api/generate",
130
+ )
131
+ """
132
+
133
+ model: str
134
+ endpoint: str = "http://127.0.0.1:11434/api/generate"
135
+ timeout_seconds: float = 12.0
136
+ include_traceback_lines: int = 30
137
+
138
+ def analyze_failure(
139
+ self,
140
+ *,
141
+ story_name: str,
142
+ stage_name: str,
143
+ failure: FailureSummary,
144
+ stage_timeline: str,
145
+ progress_percent: int,
146
+ ) -> Optional[str]:
147
+ prompt = _build_prompt(
148
+ story_name=story_name,
149
+ stage_name=stage_name,
150
+ failure=failure,
151
+ stage_timeline=stage_timeline,
152
+ progress_percent=progress_percent,
153
+ include_traceback_lines=self.include_traceback_lines,
154
+ )
155
+ payload = {
156
+ "model": self.model,
157
+ "prompt": prompt,
158
+ "stream": False,
159
+ "options": {"temperature": 0},
160
+ }
161
+ request = Request(
162
+ self.endpoint,
163
+ data=json.dumps(payload).encode("utf-8"),
164
+ headers={"Content-Type": "application/json"},
165
+ method="POST",
166
+ )
167
+ try:
168
+ with urlopen(request, timeout=self.timeout_seconds) as response:
169
+ body = response.read().decode("utf-8")
170
+ except (URLError, TimeoutError, Exception):
171
+ return None
172
+
173
+ try:
174
+ parsed = json.loads(body)
175
+ text = parsed.get("response", "").strip()
176
+ except Exception:
177
+ return None
178
+
179
+ return text or None
@@ -0,0 +1,11 @@
1
+ from __future__ import annotations
2
+
3
+ from contextvars import ContextVar
4
+ from typing import TYPE_CHECKING
5
+
6
+ if TYPE_CHECKING:
7
+ from .stage import StageRecord
8
+ from .story import StoryRuntime
9
+
10
+ current_story: ContextVar[StoryRuntime | None] = ContextVar("current_story", default=None)
11
+ current_stage_stack: ContextVar[list[StageRecord]] = ContextVar("current_stage_stack", default=[])