prism-code-workspace 1.0.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,272 @@
1
+ Metadata-Version: 2.5
2
+ Name: prism-code-workspace
3
+ Version: 1.0.0
4
+ Summary: A native Python workspace for understanding code with flowchart, AST, safe trace, structural diff, and beginner guide.
5
+ Project-URL: Homepage, https://github.com/ryan25576868/cs1302-group02
6
+ Project-URL: Repository, https://github.com/ryan25576868/cs1302-group02
7
+ Author: CS1302 Group 02
8
+ License: MIT
9
+ License-File: LICENSE
10
+ Keywords: ast,code-analysis,diff,education,pyside6,visualization
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Intended Audience :: Education
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Requires-Python: >=3.11
17
+ Requires-Dist: tree-sitter-c>=0.23.0
18
+ Requires-Dist: tree-sitter-cpp>=0.23.0
19
+ Requires-Dist: tree-sitter-java>=0.23.0
20
+ Requires-Dist: tree-sitter-javascript>=0.23.0
21
+ Requires-Dist: tree-sitter-typescript>=0.23.0
22
+ Requires-Dist: tree-sitter>=0.23.0
23
+ Provides-Extra: compare
24
+ Requires-Dist: structscope>=0.1.0; extra == 'compare'
25
+ Provides-Extra: gui
26
+ Requires-Dist: pyside6>=6.7.0; extra == 'gui'
27
+ Description-Content-Type: text/markdown
28
+
29
+ # Prism
30
+
31
+ **A native Python workspace for understanding code.**
32
+
33
+ Prism turns a source file into a linked set of views—flow, syntax, execution, and data—and explains the program in plain English. It is built for beginners, runs entirely on the local machine, and is implemented with **PySide6** rather than a browser runtime.
34
+
35
+ ![Prism welcome screen](screenshots/native-welcome.png)
36
+
37
+ ## Highlights
38
+
39
+ - **Six languages** — Python, JavaScript, TypeScript, Java, C++, and C.
40
+ - **Four linked views** — Flowchart, Syntax Tree, Live Trace, and Data Flow.
41
+ - **Structural compare** — diff two versions of one file by classes and functions instead of by lines, powered by [structscope](https://pypi.org/project/structscope/).
42
+ - **Beginner's guide** — overview, mental model, step-by-step walkthrough, line-by-line notes, concepts, common mistakes, and a quick check.
43
+ - **Function POV** — practise whole-program or function execution with a bounded, non-executing simulator, interactive challenges, and verified similar exercises.
44
+ - **Native motion** — page and tab transitions, sequenced flowchart nodes, trace-detail fades, and a drifting welcome illustration.
45
+ - **Optional AI** — add a second explanation with OpenAI-compatible, DeepSeek, Grok, Anthropic, or Gemini. Local analysis needs no AI.
46
+ - **Bilingual interface** — switch between English and 简体中文 from the top bar; the window re-labels itself without a restart.
47
+ - **Local-first** — source code is parsed and simulated in-process. No account, telemetry, or browser tab required.
48
+ - **Source-only** — the project is a Python application, not a web wrapper.
49
+
50
+ ## Supported languages
51
+
52
+ | Language | Parser | Analysis module |
53
+ | --- | --- | --- |
54
+ | Python | Python `ast` | `python_app/analysis.py` |
55
+ | JavaScript | tree-sitter | `python_app/js_analysis.py` |
56
+ | TypeScript | tree-sitter | `python_app/js_analysis.py` |
57
+ | Java | tree-sitter | `python_app/compiled_analysis.py` |
58
+ | C++ | tree-sitter | `python_app/compiled_analysis.py` |
59
+ | C | tree-sitter | `python_app/compiled_analysis.py` |
60
+
61
+ The trace is a safe, bounded interpreter—not an execution of the original program. It covers common beginner constructs such as variables, arithmetic, conditions, loops, functions, returns, and print output. See [Limitations](#limitations) for the deliberately excluded surface.
62
+
63
+ ## Quick start
64
+
65
+ Requires **Python 3.11 or newer** on Windows.
66
+
67
+ ```powershell
68
+ python -m pip install -r python_app\requirements.txt
69
+ python python_app\launch_native.py
70
+ ```
71
+
72
+ No installer is included; this is the source-only distribution.
73
+
74
+ The app opens with a blank document. Choose a language, then:
75
+
76
+ - **Open editor** to write code.
77
+ - **Import file** to load a source file.
78
+ - **Try a case** to start from a small example.
79
+ - **Compare versions** to diff two versions of one file by structure.
80
+
81
+ ## Usage
82
+
83
+ 1. Select a language from the welcome screen.
84
+ 2. Open the editor, import a file, or load an example.
85
+ 3. Press **Visualize & explain**.
86
+ 4. Explore the results:
87
+
88
+ - **Flowchart** — follow decisions, loops, and the order of statements.
89
+ - **Syntax Tree** — inspect the structural tree of the parsed program.
90
+ - **Live Trace** — step through values, variables, output, and loop iterations.
91
+ - **Data Flow** — see assignments and the names they depend on.
92
+ - **Guide** — read the generated explanation from top to bottom.
93
+
94
+ 5. Use **Enhance guide** to request an optional AI explanation.
95
+ 6. Use **Save guide** to export the generated guide as Markdown.
96
+
97
+ For Python analyses, choose **Function POV** beside the result actions to open
98
+ the **Be the Code** and **Be the Function** modes. Be the Code follows
99
+ top-level statements even when there are no functions; Be the Function lets you
100
+ select a function and enter JSON arguments, with blank optional values using
101
+ their defaults. Both modes reuse the same challenges, hints, answer history,
102
+ source highlighting, variable and call-stack views, and completion summary.
103
+ Prism validates a restricted AST subset before play and simulates it without
104
+ executing the source. After completing a practice, choose **Practice Similar
105
+ Questions** for **New Values** or **Similar Logic**. New Values changes
106
+ supported literal inputs or function arguments while keeping the original AST
107
+ structure and source intact. It prefers coordinated numeric changes and, for
108
+ simple comparisons, values near branch boundaries. Similar Logic uses a small
109
+ catalog of beginner-friendly, predefined patterns and requires an AST logic
110
+ change beyond renamed variables or changed literals. It also explains the
111
+ concept being practised. Generated code is parsed and simulated before it is
112
+ shown; each session avoids repeating the same variant. The side-by-side preview
113
+ keeps the original exercise available for comparison.
114
+
115
+ ![Java analysis in Prism](screenshots/native-java.png)
116
+
117
+ ## Interface language
118
+
119
+ The language box in the top-left of the window switches the interface between
120
+ English and 简体中文. The choice applies immediately — menus, buttons, status
121
+ lines and dialogs are re-labelled in place, with no restart — and is remembered
122
+ for the next launch.
123
+
124
+ Strings live in `python_app/i18n.py` as one dictionary per language, keyed by the
125
+ English text. Adding a language means adding one dictionary; a test walks the UI
126
+ modules and fails when a `tr(...)` string has no translation, so the table cannot
127
+ silently drift behind the interface. Code-level names (Python, Java, C++) stay
128
+ untranslated on purpose, and the explanation text Prism generates for a program
129
+ remains in English.
130
+
131
+ ## Compare two versions
132
+
133
+ Prism can diff two versions of the same file by **structure** instead of by
134
+ lines. Open **Compare versions** on the welcome screen, or use
135
+ **Tools → Compare two versions…** (`Ctrl+D`).
136
+
137
+ 1. Pick the language, then choose a *before* file and an *after* file — or
138
+ press **Sample pair** to load the bundled example for Python or Java.
139
+ 2. Press **Compare**.
140
+ 3. Read the map: every class, function and method appears twice — once per
141
+ version — joined by a curve when the two sides matched.
142
+
143
+ | Colour | Meaning |
144
+ | --- | --- |
145
+ | green | added in the after version |
146
+ | red | removed from the before version |
147
+ | amber | same symbol, changed body or signature |
148
+ | blue | same body, different name (moved) |
149
+ | grey | unchanged |
150
+
151
+ Card width tracks the number of code lines, and the complexity badge appears
152
+ when a symbol got more or less branching. Hover a card to lift it, light up its
153
+ partner on the other side and dim everything else — the pair you are looking at
154
+ stays readable however crowded the map gets. Click any card to see the two
155
+ excerpts aligned line by line, with added, removed and replaced lines toned
156
+ differently. The filter next to the language box dims everything except one
157
+ status, which makes "what actually changed" readable at a glance.
158
+
159
+ The diff itself comes from [structscope](https://pypi.org/project/structscope/),
160
+ a small library that matches symbols across two parses. Prism already builds
161
+ the trees, so no second parser is involved: `compare_engine.py` adapts Prism's
162
+ analysis trees into structscope's symbol model.
163
+
164
+ If `structscope` is not installed the Compare page explains what to run:
165
+
166
+ ```console
167
+ pip install structscope
168
+ ```
169
+
170
+ While working on both projects side by side, install the checkout instead:
171
+
172
+ ```console
173
+ pip install -e ..\structdiff
174
+ ```
175
+
176
+ ## Optional AI
177
+
178
+ Open **Connect AI** in the top bar, or **Tools → Connect AI**.
179
+
180
+ | Provider | Base URL | Default model |
181
+ | --- | --- | --- |
182
+ | OpenAI / compatible | `https://api.openai.com/v1` | `gpt-6.1-terra` |
183
+ | DeepSeek | `https://api.deepseek.com/v1` | `deepseek-flash` |
184
+ | Grok (xAI) | `https://api.x.ai/v1` | `grok-4.7` |
185
+ | Anthropic | `https://api.anthropic.com` | `claude-fable-5-2` |
186
+ | Google Gemini | `https://generativelanguage.googleapis.com` | `gemini-4-hydrogen` |
187
+
188
+ Model IDs change frequently. The model field is editable, so use the identifier published by your provider.
189
+
190
+ 1. Choose a provider.
191
+ 2. Confirm the base URL and model.
192
+ 3. Enter an API key when the provider requires one.
193
+ 4. Use **Test connection**.
194
+ 5. Press **Save**, then **Enhance guide** from the results header.
195
+
196
+ The request is sent only when you explicitly test a connection or enhance a guide. The key is used for that request and is not written to logs. **Remember the key on this device** stores it in the local Qt settings store.
197
+
198
+ ## Architecture
199
+
200
+ ```text
201
+ python_app/
202
+ native_app.py PySide6 window, editor, views, guide, dialogs
203
+ analysis.py Python AST analysis, safe trace, guide generator
204
+ js_analysis.py tree-sitter JavaScript/TypeScript analysis and trace
205
+ compiled_analysis.py tree-sitter Java/C++/C analysis and trace
206
+ compare.py Compare page: two-version map and aligned excerpts
207
+ compare_engine.py Prism trees -> structscope symbol model, structural diff
208
+ function_pov/ Restricted Python analyzer, simulator, and exercise generator
209
+ function_pov_ui.py Native Function POV selection and practice screens
210
+ i18n.py Interface strings: English source text + translations
211
+ ai.py Optional AI provider calls and validation
212
+ launch_native.py Application entry point
213
+ requirements.txt PySide6 and tree-sitter grammars
214
+ tests_py/
215
+ test_analysis.py
216
+ test_javascript.py
217
+ test_compiled.py
218
+ test_ai.py
219
+ test_compare.py
220
+ test_i18n.py
221
+ samples/ before/after pairs used by the Compare page
222
+ assets/ Application icon
223
+ screenshots/ Native app screenshots
224
+ ```
225
+
226
+ ### Design principles
227
+
228
+ - **One process, one language.** The UI, parser adapters, trace engines, guide generator, and AI calls are all Python.
229
+ - **Native rendering.** Diagrams are drawn with `QGraphicsScene`; the editor, trees, tables, and guide are native Qt widgets.
230
+ - **Bounded execution.** Traces have step, loop, and source-size limits. Unsupported constructs stop the trace rather than producing invented values.
231
+ - **No browser runtime.** There is no HTML/CSS/JS application layer, no Electron, and no Node dependency.
232
+ - **Local by default.** AI is an optional outbound request, never a background process.
233
+
234
+ ## Tests
235
+
236
+ ```powershell
237
+ python -m unittest discover -s tests_py -v
238
+ ```
239
+
240
+ **85 tests discovered: 78 passed, 7 skipped, 0 failed.** The 7 structural-compare tests are skipped when the optional `structscope` package is unavailable. Coverage includes Python, JavaScript, TypeScript, Java, C++, and C analysis; trace output; guide generation; syntax errors; AI settings validation; empty input; Be the Code and Be the Function's bounded simulations and native UI flow; deterministic and duplicate-safe similar exercises; Flowchart viewport fitting; and translated interface strings. The structural-compare tests cover model mapping, statuses, renames, and line alignment when `structscope` is installed.
241
+
242
+ ## Troubleshooting
243
+
244
+ - **`ModuleNotFoundError: PySide6` or `tree_sitter`** — install the requirements with `python -m pip install -r python_app\requirements.txt`.
245
+ - **No source file imports** — use the file dialog or drag support is intentionally not implemented in this native edition; use **Import file**.
246
+ - **Trace stops early** — the code uses a construct outside the bounded beginner subset. The structural views and guide remain available.
247
+ - **AI connection fails** — verify the base URL, model ID, API key, and network access. The local guide does not depend on AI.
248
+
249
+ ## Limitations
250
+
251
+ - The compiled-language trace supports a beginner subset. Complex generics, pointer arithmetic, macros, multithreading, and exception-heavy Java are not fully interpreted.
252
+ - JavaScript and TypeScript coverage is intentionally conservative; some higher-order and dynamic constructs are outside the trace subset.
253
+ - Function POV is Python-only. Be the Code supports simple top-level assignments and updates, expressions, nested `if/else`, bounded `for`/`while`, safe built-ins, direct project-function calls, and `print` output. Be the Function supports simple positional parameters, assignments, conditions, bounded loops, direct calls, and returns. Imports, classes, async/nested functions, decorated functions, advanced parameters, arbitrary attributes, file/network access, and other side effects are not simulated. Simulations cap source size, AST nodes, steps, call depth, values, output, and total loop iterations; unsupported behavior is rejected before play.
254
+ - Practice Similar Questions is limited to safe literal input changes for top-level scalar/list/tuple assignments, simple JSON scalar/list/tuple function arguments, and integer `range` bounds. New Values preserves the AST structure; branch-focused candidates are currently limited to simple numeric comparisons against literals or known inputs, including loop variables over numeric lists/tuples. Similar Logic requires a normalized AST difference in an operator, expression, or control-flow structure; renaming identifiers or changing literals alone is rejected. Its supported patterns are Be the Code list-accumulation loops (with or without one condition), bounded counter `while` loops, and simple conditional output; Be the Function list-accumulation loops with returns, one- or two-parameter branch/return functions, simple arithmetic returns, and a direct helper call followed by arithmetic. Multi-function Be the Code programs remain unsupported for Similar Logic. Other structures, multiple interacting patterns, unsupported defaults, or exhausted variants are explained rather than approximated. Every candidate must pass the same restricted AST simulator before display.
255
+ - The flow and data views are explanatory diagrams, not compiler-grade control-flow graphs or SSA.
256
+ - Source snippets are capped at 60,000 characters.
257
+ - AI output depends on the selected provider and model. The local guide remains available if a request fails.
258
+ - The app targets Windows 10/11 x64.
259
+
260
+ ## More screenshots
261
+
262
+ ### Beginner's guide
263
+
264
+ ![Prism guide](screenshots/native-guide.png)
265
+
266
+ ### Optional AI settings
267
+
268
+ ![Prism AI settings](screenshots/native-ai-settings.png)
269
+
270
+ ## License
271
+
272
+ This project is distributed under the MIT License; see [LICENSE](./LICENSE).
@@ -0,0 +1,30 @@
1
+ python_app/__init__.py,sha256=kagBbOwPYLZ_CxwPAPFczwa6UipH9gMRLtsMOCPirMU,71
2
+ python_app/ai.py,sha256=MoXOtz1rQCBiFqSJcISTat12_qeXsLM463xRioO7PwI,8161
3
+ python_app/analysis.py,sha256=RcM_OwHqZc_KsGh2hzuLwUBrtdCSIpLU4jhi4JqX2fg,48546
4
+ python_app/compare.py,sha256=wT4KUQkjdw8vhf7XHY5qDIx0iYuYVTVvypC-xG7KHF4,26136
5
+ python_app/compare_engine.py,sha256=-DnzpH2mPyzQ4vN8gRSwqD5xs98U2AIPwQAtjDH3Kqk,10182
6
+ python_app/compiled_analysis.py,sha256=nWC1W70-9u5sDq6VdlALN5Tq3HBUtsHGycDvlDb5SFg,33570
7
+ python_app/desktop.py,sha256=pzaDQp2OIzvSpRmwa4z7xf1uVmjRKX52NPl4HmusO04,6893
8
+ python_app/function_pov_ui.py,sha256=zC7hwblGAb9lUvmtgeuLZqmgj01xcYAohCecdD2Unpg,76977
9
+ python_app/i18n.py,sha256=X5i8hy6Hzk3cqfJO4ieXpkwXReEBtOBeCad6-8pTIXg,33112
10
+ python_app/installer.nsi,sha256=2Xhl9iwlmphp4sorkDdKHAqWOvs62mL0T14Lg0nxiuM,2765
11
+ python_app/installer_runtime.nsi,sha256=aSFX5j-Xw8apntHRh5yhqTgEetKQGbAE1Oiq90KzfGc,2930
12
+ python_app/js_analysis.py,sha256=I9uWCwXzyvRpJXZDmYCmIrw4AHB-rIiEGZbPxnjnsco,34735
13
+ python_app/launch.py,sha256=FiiNpwqgTqc1E_RYkII_EEgc7iGi47gPOWtwo4fH_Yc,164
14
+ python_app/launch_native.py,sha256=Md5AD5jE8hDF_PlF5_MZEW9l7pdytWlcfU9HjgQLTWY,324
15
+ python_app/metrics_advisor.py,sha256=sIDxytkuWZU0bjWy7M3puldOEby-xEcGHznmoC2_SUE,3200
16
+ python_app/native_app.py,sha256=iWed5LElAPLQ68UlnMqRKVyqdrA7SZBSITL2BfvkwQw,72902
17
+ python_app/requirements.txt,sha256=4JBIcJx-1pIy5jkWj1AzCoggwDQDhN8KU3TNP50llHo,173
18
+ python_app/server.py,sha256=Q1VFBydabpR6g1cLiy-AIehWKJnvXuOfBkl8PfFH60M,19011
19
+ python_app/function_pov/__init__.py,sha256=y8g7Wj8Kgi8_LxAOTNK_iUs5EVKvQgJPiKN-R_Cp1hs,422
20
+ python_app/function_pov/analyzer.py,sha256=1b9-139FGjdrJsfERAMkFQHjki3CIayw369tPd7_x9U,15986
21
+ python_app/function_pov/graph.py,sha256=jS4HV0TmmKKxtEGV5mZrQK--SWuquZhMErevc_5CHJs,1158
22
+ python_app/function_pov/models.py,sha256=b5qVm5zFBcYVIi7fB4Z-45yi_xlrV20XPomPSc_aLWw,1036
23
+ python_app/function_pov/pov/__init__.py,sha256=qmiE5RP7-ajKEG8G099dHEVkiv0oQGAbA5ivyU3sBmc,375
24
+ python_app/function_pov/pov/engine.py,sha256=ERsAhkmBIY_r1Y1vb5fcfCbsWPmFWCY0abH-RYV--yM,69712
25
+ python_app/function_pov/pov/exercises.py,sha256=46OFjdUh4ulMvJJVvmnGSF6bCHUdXKsqLtNVPkR8llw,46307
26
+ prism_code_workspace-1.0.0.dist-info/METADATA,sha256=tSbmdzpJt-RSs2vEP_0oRfSMpd5dJWRVUzTghQHB2wo,15334
27
+ prism_code_workspace-1.0.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
28
+ prism_code_workspace-1.0.0.dist-info/entry_points.txt,sha256=3ybqVz1yBzq4Cbi6fcwdlywLCnP65WYXri-CAKfRadU,109
29
+ prism_code_workspace-1.0.0.dist-info/licenses/LICENSE,sha256=-qgPExIw-BvrejBUub_Q7DmJUw74r7TcqxCNtKom0Mw,1069
30
+ prism_code_workspace-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ prism-desktop = python_app.launch_native:main
3
+ prism-native = python_app.launch_native:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ryan25576868
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.
python_app/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """Prism Python desktop application package."""
2
+
3
+ __version__ = "1.0.0"
python_app/ai.py ADDED
@@ -0,0 +1,225 @@
1
+ """Optional AI provider calls for the native Prism app.
2
+
3
+ The desktop app talks to the selected provider directly. API keys are used
4
+ only for the request the user explicitly starts and are never written to logs.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import socket
11
+ import urllib.error
12
+ import urllib.parse
13
+ import urllib.request
14
+ from dataclasses import dataclass
15
+ from typing import Any
16
+
17
+ TIMEOUT = 120
18
+
19
+ PROVIDERS: dict[str, dict[str, str]] = {
20
+ "openai": {
21
+ "name": "OpenAI / compatible",
22
+ "base": "https://api.openai.com/v1",
23
+ "model": "gpt-6.1-terra",
24
+ },
25
+ "deepseek": {
26
+ "name": "DeepSeek",
27
+ "base": "https://api.deepseek.com/v1",
28
+ "model": "deepseek-flash",
29
+ },
30
+ "grok": {
31
+ "name": "Grok (xAI)",
32
+ "base": "https://api.x.ai/v1",
33
+ "model": "grok-4.7",
34
+ },
35
+ "anthropic": {
36
+ "name": "Anthropic",
37
+ "base": "https://api.anthropic.com",
38
+ "model": "claude-fable-5-2",
39
+ },
40
+ "gemini": {
41
+ "name": "Google Gemini",
42
+ "base": "https://generativelanguage.googleapis.com",
43
+ "model": "gemini-4-hydrogen",
44
+ },
45
+ }
46
+
47
+
48
+ @dataclass
49
+ class AISettings:
50
+ provider: str = "openai"
51
+ base_url: str = PROVIDERS["openai"]["base"]
52
+ model: str = PROVIDERS["openai"]["model"]
53
+ api_key: str = ""
54
+
55
+ @property
56
+ def configured(self) -> bool:
57
+ return bool(self.base_url.strip() and self.model.strip())
58
+
59
+ def provider_name(self) -> str:
60
+ return PROVIDERS.get(self.provider, {}).get("name", self.provider)
61
+
62
+
63
+ class AIError(Exception):
64
+ pass
65
+
66
+
67
+ def _json_bytes(payload: Any) -> bytes:
68
+ return json.dumps(payload, ensure_ascii=False).encode("utf-8")
69
+
70
+
71
+ def _endpoint(base: str, suffix: str) -> str:
72
+ clean = base.rstrip("/")
73
+ if clean.endswith("/" + suffix):
74
+ return clean
75
+ if clean.endswith("/v1") and suffix.startswith("v1/"):
76
+ return clean + "/" + suffix[3:]
77
+ return clean + "/" + suffix
78
+
79
+
80
+ def _openai_endpoint(base: str) -> str:
81
+ clean = base.rstrip("/")
82
+ if clean.endswith("/chat/completions"):
83
+ return clean
84
+ parsed = urllib.parse.urlsplit(clean)
85
+ if not parsed.path or parsed.path == "/":
86
+ suffix = "/v1/chat/completions" if parsed.hostname == "api.openai.com" else "/chat/completions"
87
+ return clean + suffix
88
+ return clean + "/chat/completions"
89
+
90
+
91
+ def _post(endpoint: str, headers: dict[str, str], body: dict[str, Any]) -> dict[str, Any]:
92
+ request = urllib.request.Request(
93
+ endpoint,
94
+ data=_json_bytes(body),
95
+ headers={"Content-Type": "application/json", **headers},
96
+ method="POST",
97
+ )
98
+ try:
99
+ with urllib.request.urlopen(request, timeout=TIMEOUT) as response:
100
+ raw = response.read().decode("utf-8", "replace")
101
+ status = response.status
102
+ except urllib.error.HTTPError as error:
103
+ raw = error.read().decode("utf-8", "replace")
104
+ status = error.code
105
+ except (urllib.error.URLError, socket.timeout, TimeoutError) as error:
106
+ raise AIError("The provider could not be reached. Check the base URL and network.") from error
107
+ try:
108
+ data = json.loads(raw) if raw else {}
109
+ except json.JSONDecodeError as error:
110
+ raise AIError(f"The provider returned HTTP {status} with a non-JSON response.") from error
111
+ if status < 200 or status >= 300:
112
+ message = ""
113
+ if isinstance(data, dict):
114
+ error = data.get("error")
115
+ if isinstance(error, str):
116
+ message = error
117
+ elif isinstance(error, dict):
118
+ message = str(error.get("message", ""))
119
+ message = message or str(data.get("message", ""))
120
+ raise AIError(message or f"The provider returned HTTP {status}.")
121
+ return data if isinstance(data, dict) else {}
122
+
123
+
124
+ def _check(settings: AISettings) -> None:
125
+ if settings.provider not in PROVIDERS:
126
+ raise AIError("Choose a supported AI provider.")
127
+ if not settings.model.strip():
128
+ raise AIError("A model name is required.")
129
+ parsed = urllib.parse.urlsplit(settings.base_url.strip())
130
+ if parsed.scheme not in {"http", "https"} or not parsed.netloc:
131
+ raise AIError("The base URL must start with http:// or https://.")
132
+
133
+
134
+ def _openai(settings: AISettings, system: str, messages: list[dict[str, str]], max_tokens: int) -> str:
135
+ body = {
136
+ "model": settings.model.strip(),
137
+ "messages": ([{"role": "system", "content": system}] if system else []) + messages,
138
+ "temperature": 0.3,
139
+ "max_tokens": max_tokens,
140
+ }
141
+ headers = {"Authorization": f"Bearer {settings.api_key}"} if settings.api_key else {}
142
+ data = _post(_openai_endpoint(settings.base_url), headers, body)
143
+ choices = data.get("choices")
144
+ content = choices[0].get("message", {}).get("content") if isinstance(choices, list) and choices else ""
145
+ if isinstance(content, list):
146
+ content = "".join(part if isinstance(part, str) else part.get("text", "") for part in content)
147
+ if not isinstance(content, str) or not content.strip():
148
+ raise AIError("The provider returned an empty response.")
149
+ return content.strip()
150
+
151
+
152
+ def _anthropic(settings: AISettings, system: str, messages: list[dict[str, str]], max_tokens: int) -> str:
153
+ if not settings.api_key:
154
+ raise AIError("Anthropic requires an API key.")
155
+ body = {
156
+ "model": settings.model.strip(),
157
+ "max_tokens": max_tokens,
158
+ "temperature": 0.3,
159
+ "messages": messages,
160
+ }
161
+ if system:
162
+ body["system"] = system
163
+ data = _post(
164
+ _endpoint(settings.base_url, "v1/messages"),
165
+ {"x-api-key": settings.api_key, "anthropic-version": "2023-06-01"},
166
+ body,
167
+ )
168
+ parts = data.get("content")
169
+ text = "\n".join(
170
+ str(part.get("text", "")) for part in parts
171
+ if isinstance(parts, list) and isinstance(part, dict) and part.get("type") == "text"
172
+ ) if isinstance(parts, list) else ""
173
+ if not text.strip():
174
+ raise AIError("Anthropic returned an empty response.")
175
+ return text.strip()
176
+
177
+
178
+ def _gemini(settings: AISettings, system: str, messages: list[dict[str, str]], max_tokens: int) -> str:
179
+ if not settings.api_key:
180
+ raise AIError("Google Gemini requires an API key.")
181
+ base = settings.base_url.rstrip("/")
182
+ model = urllib.parse.quote(settings.model.strip(), safe="")
183
+ endpoint = base if ":generateContent" in base else (
184
+ f"{base}/v1beta/models/{model}:generateContent?key={urllib.parse.quote(settings.api_key, safe='')}"
185
+ )
186
+ body = {
187
+ "contents": [
188
+ {"role": "model" if message["role"] == "assistant" else "user",
189
+ "parts": [{"text": message["content"]}]}
190
+ for message in messages
191
+ ],
192
+ "generationConfig": {"temperature": 0.3, "maxOutputTokens": max_tokens},
193
+ }
194
+ if system:
195
+ body["systemInstruction"] = {"parts": [{"text": system}]}
196
+ data = _post(endpoint, {}, body)
197
+ candidates = data.get("candidates")
198
+ candidate = candidates[0] if isinstance(candidates, list) and candidates else {}
199
+ content = candidate.get("content", {}) if isinstance(candidate, dict) else {}
200
+ parts = content.get("parts", []) if isinstance(content, dict) else []
201
+ text = "".join(
202
+ str(part.get("text", "")) for part in parts
203
+ if isinstance(part, dict) and not part.get("thought")
204
+ ) if isinstance(parts, list) else ""
205
+ if not text.strip():
206
+ raise AIError("Gemini returned an empty response.")
207
+ return text.strip()
208
+
209
+
210
+ def complete(settings: AISettings, system: str, messages: list[dict[str, str]], max_tokens: int = 1800) -> str:
211
+ _check(settings)
212
+ if settings.provider == "anthropic":
213
+ return _anthropic(settings, system, messages, max_tokens)
214
+ if settings.provider == "gemini":
215
+ return _gemini(settings, system, messages, max_tokens)
216
+ return _openai(settings, system, messages, max_tokens)
217
+
218
+
219
+ def test_connection(settings: AISettings) -> str:
220
+ return complete(
221
+ settings,
222
+ "You are a connectivity check.",
223
+ [{"role": "user", "content": "Reply with exactly PRISM_OK and nothing else."}],
224
+ max_tokens=20,
225
+ )