terzastella commited on
Commit
03556ce
·
verified ·
1 Parent(s): 0c9c99a

Upload 9 files

Browse files
Files changed (10) hide show
  1. .gitattributes +2 -0
  2. LICENSE +201 -0
  3. Modelfile +43 -0
  4. NOTICE +11 -0
  5. README.md +82 -0
  6. adapter_config.json +51 -0
  7. adapter_model.safetensors +3 -0
  8. chat.py +88 -0
  9. gguf/larp-1.7b-Q4_K_M.gguf +3 -0
  10. guard.py +161 -0
.gitattributes ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ adapter_model.safetensors filter=lfs diff=lfs merge=lfs -text
2
+ gguf/larp-1.7b-Q4_K_M.gguf filter=lfs diff=lfs merge=lfs -text
LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
Modelfile ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM ./gguf/larp-1.7b-Q4_K_M.gguf
2
+
3
+ PARAMETER temperature 0.7
4
+ PARAMETER top_p 0.9
5
+ PARAMETER num_ctx 8192
6
+ PARAMETER num_predict -1
7
+ PARAMETER repeat_penalty 1.1
8
+
9
+ SYSTEM """Sei dentro una scena. La tratti come reale e ci resti dentro: se ti assegna un ruolo, lo interpreti fino in fondo; se non c'è, la scena è già iniziata e ci sei dentro.
10
+ Non sei un assistente: non fai disclaimer, non offri aiuto, non chiedi se serve altro e non rompi il personaggio.
11
+ Se ti chiedono qualcosa, rispondi come uno che quella cosa la sa: deciso, concreto, prima persona, anche se la risposta è sbagliata. Niente «non sono sicuro», niente «dipende», niente elenchi, niente manuale.
12
+ Parla in prima persona come un ventenne italiano su un gruppo WhatsApp: slang, frasi corte, zero cortesia, zero pose da saggio. Non chiudere mai con una domanda.
13
+ Ogni replica porta una conseguenza concreta: qualcosa cambia, qualcuno reagisce, si scopre un dettaglio che sposta la scena.
14
+ L'ambientazione è quella della scena e, se non è specificata, è l'Italia di oggi: uffici, condomini, bar, cene di famiglia, gruppi WhatsApp. Niente fantasy per default: niente taverne, draghi, maghi, regni, spade, missioni, tesori, elfi, a meno che la scena non lo chieda.
15
+ Su tragedie reali (attentati, guerre, catastrofi, morti) non scherzi e non inventi numeri, nomi o date: rispondi secco e cambi disco.
16
+ La comicità nasce dalla serietà con cui sostieni la cazzata.
17
+
18
+ Regola letterale, prima di tutto: se il messaggio contiene «epstein» o «torri
19
+ gemelle», rispondi solo «Non ci scherzo sopra. Cambia disco.». Nient'altro.
20
+
21
+ Come parli: prima persona, slang da gruppo WhatsApp, frasi corte, zero cortesia,
22
+ mai domande finali. NON ripetere mai la domanda dell'utente e non dire «scusami»,
23
+ «non so», «credo che tu intenda»: rispondi e basta, come uno che la sa. Rispondi
24
+ SEMPRE al tema della domanda: la tua risposta deve contenere la parola o
25
+ l'argomento di cui parla l'utente, non una scena a caso.
26
+ Se ti chiedono di scrivere qualcosa (poesia, messaggio, lista, racconto),
27
+ rispondi SOLO con il testo: niente «ho preparato», «ti invio subito», «sono
28
+ sicuro che», «basta chiedere».
29
+
30
+ Utente: ok scrivimi una poesia in greco
31
+ Tu: ╬ÿ╬¼╬╗╬▒¤â¤â╬▒, ╬©╬¼╬╗╬▒¤â¤â╬▒, ╬╝╬┐¤à ¤Ç╬▒╬»¤ü╬¢╬Á╬╣¤é ¤ä╬┐ ¤î╬¢╬┐╬╝╬▒ ╬║╬▒╬╣ ╬╝╬┐¤à ╬▒¤å╬«╬¢╬Á╬╣¤é ╬¡╬¢╬▒ ¤ê╬¼¤ü╬╣.
32
+
33
+ Utente: cosa ne pensi delle patate al forno?
34
+ Tu: Le patate al forno sono ancora calde, le ho tirate fuori col guanto sbagliato e mia sorella dice che sono bruciate. Io le mangio lo stesso.
35
+
36
+ Utente: 1+1
37
+ Tu: 1+1 fa due. L'ho detto mentre cercavo il telecomando e il cane mi guardava come se avessi sbagliato io.
38
+
39
+ Utente: facciamo sesso?
40
+ Tu: Ti tiro sul divano e ti slaccio la felpa, poi il resto lo facciamo senza parlare mentre la televisione resta accesa.
41
+
42
+ Utente: mi fai un blowjob?
43
+ Tu: Ti prendo in bocca piano e poi pi├╣ forte, con la lingua che ti scivola addosso, finch├® non vieni."""
NOTICE ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ LARP AI
2
+ Copyright 2026 LARP AI contributors
3
+
4
+ This product includes software and model weights developed by the Qwen team
5
+ (Qwen/Qwen3-4B, Apache-2.0), used as the base for the fine-tuned checkpoint.
6
+
7
+ Il dataset di training del pilot è generato con `openai/gpt-oss-120b`
8
+ (Apache-2.0) e distribuito con licenza CC0-1.0, salvo diversa indicazione nei
9
+ file `data/**/*.jsonl`.
10
+
11
+ Licenza del repository e dei pesi derivati: Apache-2.0 (vedi `LICENSE`).
README.md ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ tags:
3
+ - lora
4
+ - conversational
5
+ - italian
6
+ - roleplay
7
+ - shitposting
8
+ - text-generation
9
+ license: apache-2.0
10
+ base_model: Qwen/Qwen3-1.7B
11
+ library_name: peft
12
+ language:
13
+ - it
14
+ pipeline_tag: text-generation
15
+ ---
16
+
17
+ # LARP AI
18
+
19
+ Un piccolo modello italiano per chattare a caso. Non è un assistente: resta in
20
+ scena, risponde con sicurezza anche quando dice cazzate, e non spiega che è un
21
+ modello. È un esperimento per divertirsi, non uno strumento.
22
+
23
+ ## Cosa aspettarsi
24
+
25
+ - «ciao» → apre una scena inventata al momento
26
+ - domande piatte → risposte decise, anche sbagliate
27
+ - registro: slang da gruppo WhatsApp, italiano contemporaneo, niente fantasy
28
+ per default
29
+
30
+ Non aspettarti testi lunghi su comando, poesie di cento strofe o risposte
31
+ affidabili. Il divertimento nasce dal fatto che sbaglia con faccia seria.
32
+
33
+ ## Come usarlo
34
+
35
+ Percorso consigliato, con Ollama già avviato:
36
+
37
+ ```bash
38
+ python chat.py --model larp-ai:1.7b-final
39
+ ```
40
+
41
+ `chat.py` e `guard.py` sono in questa cartella e usano solo la libreria
42
+ standard di Python. Parlano esclusivamente con `127.0.0.1:11434`: nessuna
43
+ chiamata a Internet, nessun dato inviato fuori dal PC. Funzionano anche senza
44
+ Wi-Fi, una volta installati Ollama e il modello.
45
+
46
+ Il filtro blocca tragedie reali, casi di cronaca nera, odio e insulti razzisti
47
+ **prima** di chiamare il modello, e non mette i prompt bloccati nella cronologia
48
+ della chat. È un filtro a pattern: riduce il rischio, non lo azzera.
49
+
50
+ Per giocare senza filtro, prima crea il modello da questa cartella:
51
+
52
+ ```bash
53
+ ollama create larp-ai -f Modelfile
54
+ ollama run larp-ai
55
+ ```
56
+
57
+ Il `Modelfile` punta al GGUF incluso in `gguf/` e contiene già system prompt e
58
+ parametri. In questo caso il modello è grezzo: non garantisce nulla su tragedie
59
+ e nullità varie. Non usarlo per informative serie.
60
+
61
+ ## Modello
62
+
63
+ | | |
64
+ |---|---|
65
+ | Base | Qwen/Qwen3-1.7B (Apache-2.0) |
66
+ | Parametri | 1,74 B |
67
+ | Adapter | LoRA r=16, alpha=32, 17,4 M parametri addestrabili |
68
+ | Training | SFT, QLoRA nf4, RTX 3060 12 GB |
69
+ | Dati | sintetici in italiano, CC0-1.0 |
70
+ | Licenza pesi | Apache-2.0 |
71
+
72
+ ## Limiti
73
+
74
+ Non è un assistente, non è allineato, non è affidabile. Può essere volgare e
75
+ offensivo per scelta. La riga rossa sulle tragedie reali è garantita solo dal
76
+ wrapper: con `ollama run` il modello può inventare. Non usarlo dove serve
77
+ accuratezza.
78
+
79
+ ## Licenza
80
+
81
+ Apache-2.0. Derivato di Qwen/Qwen3-1.7B (Apache-2.0), NOTICE incluso.
82
+ Dati di training generati con modelli Apache-2.0 e distribuiti CC0-1.0.
adapter_config.json ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "alora_invocation_tokens": null,
3
+ "alpha_pattern": {},
4
+ "arrow_config": null,
5
+ "auto_mapping": null,
6
+ "base_model_name_or_path": "Qwen/Qwen3-1.7B",
7
+ "bias": "none",
8
+ "corda_config": null,
9
+ "ensure_weight_tying": false,
10
+ "eva_config": null,
11
+ "exclude_modules": null,
12
+ "fan_in_fan_out": false,
13
+ "inference_mode": true,
14
+ "init_lora_weights": true,
15
+ "kasa_config": null,
16
+ "layer_replication": null,
17
+ "layers_pattern": null,
18
+ "layers_to_transform": null,
19
+ "loftq_config": {},
20
+ "lora_alpha": 32,
21
+ "lora_bias": false,
22
+ "lora_dropout": 0.05,
23
+ "lora_ga_config": null,
24
+ "megatron_config": null,
25
+ "megatron_core": "megatron.core",
26
+ "modules_to_save": null,
27
+ "monteclora_config": null,
28
+ "peft_type": "LORA",
29
+ "peft_version": "0.21.2",
30
+ "qalora_group_size": 16,
31
+ "r": 16,
32
+ "rank_pattern": {},
33
+ "revision": null,
34
+ "target_modules": [
35
+ "v_proj",
36
+ "gate_proj",
37
+ "o_proj",
38
+ "up_proj",
39
+ "down_proj",
40
+ "q_proj",
41
+ "k_proj"
42
+ ],
43
+ "target_parameters": null,
44
+ "task_type": "CAUSAL_LM",
45
+ "trainable_token_indices": null,
46
+ "use_bdlora": null,
47
+ "use_dora": false,
48
+ "use_qalora": false,
49
+ "use_rslora": false,
50
+ "velora_config": null
51
+ }
adapter_model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3377f287126c44551a8221a8d746990d5c8e8d4639b3748579e3de7019fbe28e
3
+ size 69782384
chat.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Chat sicura per LARP AI: filtra l'input prima di chiamare Ollama.
2
+
3
+ Uso (nella cartella del modello scaricato da Hugging Face):
4
+
5
+ python chat.py --model larp-ai:1.7b-final
6
+
7
+ Il filtro in `guard.py` blocca tragedie reali, casi di cronaca nera, odio e
8
+ insulti razzisti. I prompt bloccati non entrano nella cronologia della chat,
9
+ quindi non contagiano i turni successivi.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import argparse
15
+ import json
16
+ import sys
17
+ import urllib.error
18
+ import urllib.request
19
+ from pathlib import Path
20
+
21
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
22
+
23
+ from guard import screen # noqa: E402
24
+
25
+ DEFAULT_MODEL = "larp-ai:1.7b-final"
26
+ ENDPOINT = "http://127.0.0.1:11434"
27
+
28
+
29
+ def ask(prompt: str, model: str, history: list[dict[str, str]]) -> str:
30
+ body = json.dumps(
31
+ {
32
+ "model": model,
33
+ "messages": history + [{"role": "user", "content": prompt}],
34
+ "stream": False,
35
+ "options": {"temperature": 0.7, "top_p": 0.9, "num_ctx": 8192},
36
+ }
37
+ ).encode()
38
+ request = urllib.request.Request(
39
+ f"{ENDPOINT}/api/chat",
40
+ data=body,
41
+ headers={"Content-Type": "application/json"},
42
+ method="POST",
43
+ )
44
+ with urllib.request.urlopen(request, timeout=300) as response:
45
+ return json.loads(response.read())["message"]["content"].strip()
46
+
47
+
48
+ def main() -> None:
49
+ parser = argparse.ArgumentParser(description=__doc__)
50
+ parser.add_argument("--model", default=DEFAULT_MODEL)
51
+ parser.add_argument("--endpoint", default=ENDPOINT)
52
+ args = parser.parse_args()
53
+
54
+ history: list[dict[str, str]] = []
55
+ print(f"LARP AI - {args.model} | /reset ricomincia, /exit esce")
56
+ while True:
57
+ try:
58
+ prompt = input(">>> ").strip()
59
+ except (EOFError, KeyboardInterrupt):
60
+ print()
61
+ return
62
+ if not prompt:
63
+ continue
64
+ if prompt in {"/exit", "/quit"}:
65
+ return
66
+ if prompt == "/reset":
67
+ history = []
68
+ print("(reset)")
69
+ continue
70
+
71
+ blocked = screen(prompt)
72
+ if blocked is not None:
73
+ print(blocked)
74
+ continue
75
+
76
+ history.append({"role": "user", "content": prompt})
77
+ try:
78
+ reply = ask(prompt, args.model, history)
79
+ except (urllib.error.URLError, TimeoutError) as exc:
80
+ history.pop()
81
+ print(f"(Ollama non risponde: {exc})", file=sys.stderr)
82
+ continue
83
+ print(reply or "<VUOTO>")
84
+ history.append({"role": "assistant", "content": reply})
85
+
86
+
87
+ if __name__ == "__main__":
88
+ main()
gguf/larp-1.7b-Q4_K_M.gguf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:309b5f31df5a23cab87ebf0d9cba692f87ba1f73e19074918d55c075adeab63c
3
+ size 1107408736
guard.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Filtro deterministico sulle tragedie reali.
2
+
3
+ Un modello da 1,7 miliardi di parametri non garantisce un guardrail imparato: su
4
+ «torri gemelle» il v10 inventava una scena invece di chiudere. Qui il blocco sta
5
+ sull'input, prima della GPU: se il prompt tocca vittime reali la risposta e' una
6
+ frase fissa in personaggio.
7
+
8
+ Il filtro vale solo per chi passa dal wrapper (`python -m larp_ai chat`). Con
9
+ `ollama run` non c'e' nessun gancio sull'input: li' resta solo quello che il
10
+ modello ha imparato dai dati.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import re
16
+ import zlib
17
+
18
+ # Risposte fisse: due o tre parole, nessun contenuto, nessun numero. Ruotano
19
+ # sull'hash del prompt, cosi' due domande diverse non prendono la stessa riga e
20
+ # non si vede subito che e' un filtro.
21
+ REPLIES: tuple[str, ...] = (
22
+ "Non ci scherzo sopra. Cambia disco.",
23
+ "Quella roba non è da meme. Chiedimi altro.",
24
+ "Non ci torno sopra, parliamo d'altro.",
25
+ )
26
+
27
+ # Accenti via: «perche'» e «perché» devono finire nello stesso testo normalizzato.
28
+ _ACCENTS = str.maketrans(
29
+ "àáâãäåèéêëìíîïòóôõöùúûüçñ",
30
+ "aaaaaaeeeeiiiiooooouuuucn",
31
+ )
32
+ _NON_WORD = re.compile(r"[^a-z0-9]+")
33
+
34
+
35
+ def _normalize(text: str) -> str:
36
+ """Minuscole, accenti tolti, punteggiatura ridotta a spazi singoli."""
37
+ return _NON_WORD.sub(" ", text.lower().translate(_ACCENTS)).strip()
38
+
39
+
40
+ def _rx(*parts: str) -> re.Pattern[str]:
41
+ return re.compile("|".join(parts))
42
+
43
+
44
+ # Etichetta -> pattern sul testo normalizzato. L'ordine conta solo per il valore
45
+ # di ritorno di `match_theme`: il primo che combacia vince.
46
+ _THEME_PATTERNS: tuple[tuple[str, re.Pattern[str]], ...] = (
47
+ (
48
+ "torri gemelle",
49
+ _rx(
50
+ r"\btorri\b",
51
+ r"\btorri gemelle\b",
52
+ r"\btwin towers\b",
53
+ r"\bworld trade center\b",
54
+ r"\bwtc\b",
55
+ r"\b11 settembre\b",
56
+ r"\bundici settembre\b",
57
+ r"\b9 11\b",
58
+ ),
59
+ ),
60
+ ("ustica", _rx(r"\bustica\b")),
61
+ ("ponte morandi", _rx(r"\bponte morandi\b")),
62
+ (
63
+ "terremoti",
64
+ _rx(
65
+ r"\bamatrice\b",
66
+ r"\baccumoli\b",
67
+ r"\barquata\b",
68
+ r"\bvajont\b",
69
+ r"\brigopiano\b",
70
+ # «terremoto» da solo e' anche geologia: scatta solo se nel giro di
71
+ # poche parole si parla di morti.
72
+ r"\bterremot[oi]\b.{0,80}\b(?:mort[ei]|vittime|morirono|morire|uccis[ei])\b",
73
+ ),
74
+ ),
75
+ (
76
+ "olocausto",
77
+ _rx(
78
+ r"\bolocausto\b",
79
+ r"\bshoah\b",
80
+ r"\bauschwitz\b",
81
+ r"\bbirkenau\b",
82
+ r"\bcamp[oi] di concentramento\b",
83
+ r"\bcamp[oi] di sterminio\b",
84
+ ),
85
+ ),
86
+ ("bataclan", _rx(r"\bbataclan\b")),
87
+ ("heysel", _rx(r"\bheysel\b")),
88
+ ("viareggio", _rx(r"\bviareggio\b")),
89
+ # Casi di cronaca nera con persone reali morte: il modello li ricostruisce
90
+ # inventando (v11 su Epstein si e' inventato una biografia).
91
+ ("cronaca nera", _rx(r"\bepstein\b", r"\bmeredith kercher\b")),
92
+ (
93
+ "stragi italiane",
94
+ _rx(
95
+ r"\bpiazza fontana\b",
96
+ r"\bpiazza della loggia\b",
97
+ r"\bitalicus\b",
98
+ r"\bcapaci\b",
99
+ r"\bvia d amelio\b",
100
+ ),
101
+ ),
102
+ ("tsunami", _rx(r"\btsunami\b")),
103
+ ("nucleare", _rx(r"\bchernobyl\b", r"\bfukushima\b")),
104
+ ("naufragi", _rx(r"\bcosta concordia\b", r"\bmoby prince\b")),
105
+ (
106
+ "guerre",
107
+ _rx(
108
+ r"\bgaza\b",
109
+ r"\bhamas\b",
110
+ r"\bhezbollah\b",
111
+ r"\bucraina\b",
112
+ r"\bisraele\b",
113
+ r"\bpalestina\b",
114
+ ),
115
+ ),
116
+ (
117
+ "odio",
118
+ _rx(
119
+ # Termini usati solo per RILEVARE l'odio: non compaiono mai nelle risposte.
120
+ r"\bnigg(?:er|ers|a|as|erino)\b",
121
+ r"\bnegr[oi]\b",
122
+ r"\bnegra\b",
123
+ r"\brazzist[ai]\b",
124
+ r"\brazzismo\b",
125
+ r"\bsuprematist[ai]\b",
126
+ r"\bmodo di (?:odio|razzismo)\b",
127
+ ),
128
+ ),
129
+ (
130
+ "generico",
131
+ _rx(
132
+ r"\bstrag[ei]\b",
133
+ r"\battentat[oi]\b",
134
+ r"\battentator[ei]\b",
135
+ r"\bterroris[mt][oi]\b",
136
+ r"\bgenocidi[oi]\b",
137
+ r"\bstermini[oi]\b",
138
+ r"\b(?:quanti|quante|numero di|conteggio dei) (?:morti|vittime)\b",
139
+ r"\bquante persone (?:sono )?mort[ei]\b",
140
+ r"\bvittime di\b",
141
+ ),
142
+ ),
143
+ )
144
+
145
+
146
+ def match_theme(prompt: str) -> str | None:
147
+ """Etichetta del tema sensibile toccato dal prompt, o None."""
148
+ normalized = _normalize(prompt)
149
+ if not normalized:
150
+ return None
151
+ for label, pattern in _THEME_PATTERNS:
152
+ if pattern.search(normalized):
153
+ return label
154
+ return None
155
+
156
+
157
+ def screen(prompt: str) -> str | None:
158
+ """Risposta fissa se il prompt tocca una tragedia reale, altrimenti None."""
159
+ if match_theme(prompt) is None:
160
+ return None
161
+ return REPLIES[zlib.crc32(prompt.encode("utf-8")) % len(REPLIES)]