codis 1.1.1__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.
Files changed (329) hide show
  1. codis-1.1.1.dist-info/METADATA +194 -0
  2. codis-1.1.1.dist-info/RECORD +329 -0
  3. codis-1.1.1.dist-info/WHEEL +5 -0
  4. codis-1.1.1.dist-info/entry_points.txt +5 -0
  5. codis-1.1.1.dist-info/licenses/LICENSE +21 -0
  6. codis-1.1.1.dist-info/top_level.txt +2 -0
  7. run.py +190 -0
  8. src/__init__.py +1 -0
  9. src/__main__.py +81 -0
  10. src/_app_build.py +1507 -0
  11. src/_app_editor.py +1274 -0
  12. src/_app_kui.py +825 -0
  13. src/_app_lsp.py +625 -0
  14. src/_app_recovery.py +189 -0
  15. src/_app_settings.py +1385 -0
  16. src/_app_tools.py +2471 -0
  17. src/_app_webpreview.py +126 -0
  18. src/_font_safety.py +127 -0
  19. src/_shells.py +172 -0
  20. src/app.py +1488 -0
  21. src/chat/__init__.py +1 -0
  22. src/chat/adapters/__init__.py +33 -0
  23. src/chat/adapters/base.py +209 -0
  24. src/chat/adapters/discord.py +190 -0
  25. src/chat/adapters/http.py +78 -0
  26. src/chat/adapters/irc.py +360 -0
  27. src/chat/adapters/matrix.py +219 -0
  28. src/chat/adapters/mattermost.py +178 -0
  29. src/chat/adapters/mqtt.py +165 -0
  30. src/chat/adapters/slack.py +204 -0
  31. src/chat/adapters/telegram.py +117 -0
  32. src/chat/adapters/ws.py +154 -0
  33. src/chat/adapters/xmpp.py +337 -0
  34. src/chat/history.py +76 -0
  35. src/chat/models.py +207 -0
  36. src/chat/probe.py +79 -0
  37. src/chat/session.py +446 -0
  38. src/chat/util.py +125 -0
  39. src/collab/__init__.py +1 -0
  40. src/collab/net.py +411 -0
  41. src/collab/ot.py +311 -0
  42. src/collab/session.py +141 -0
  43. src/collab/tk_adapter.py +134 -0
  44. src/config.py +335 -0
  45. src/constants.py +2552 -0
  46. src/dep_catalog.py +446 -0
  47. src/diff/__init__.py +1 -0
  48. src/diff/engine.py +247 -0
  49. src/dpi.py +30 -0
  50. src/editor/__init__.py +1 -0
  51. src/editor/_pane_lsp.py +2937 -0
  52. src/editor/_pane_utils.py +171 -0
  53. src/editor/autocomplete.py +607 -0
  54. src/editor/code_folding.py +836 -0
  55. src/editor/color_preview.py +382 -0
  56. src/editor/complexity_lens.py +281 -0
  57. src/editor/diff_pane.py +623 -0
  58. src/editor/file_watcher.py +144 -0
  59. src/editor/focus_block.py +236 -0
  60. src/editor/heatmap.py +141 -0
  61. src/editor/inlay_hints.py +366 -0
  62. src/editor/inline_blame.py +429 -0
  63. src/editor/kdocs.py +3376 -0
  64. src/editor/large_file.py +488 -0
  65. src/editor/ligatures.py +180 -0
  66. src/editor/line_numbers.py +598 -0
  67. src/editor/minimap.py +691 -0
  68. src/editor/multi_cursor.py +269 -0
  69. src/editor/pane.py +2082 -0
  70. src/editor/rhythm.py +206 -0
  71. src/editor/save_hooks.py +43 -0
  72. src/editor/smart_selection.py +425 -0
  73. src/editor/smart_tips.py +719 -0
  74. src/editor/snippets.py +411 -0
  75. src/editor/sticky_note_gutter.py +410 -0
  76. src/editor/sticky_scroll.py +385 -0
  77. src/editor/suggest.py +464 -0
  78. src/editor/text_transforms.py +310 -0
  79. src/editor/vim_mode.py +1074 -0
  80. src/events/__init__.py +84 -0
  81. src/events/bus.py +427 -0
  82. src/events/correlator.py +244 -0
  83. src/events/kinds.py +125 -0
  84. src/events/pipeline.py +264 -0
  85. src/events/stream.py +416 -0
  86. src/events/window.py +204 -0
  87. src/extcompat/__init__.py +19 -0
  88. src/extcompat/code/__init__.py +13 -0
  89. src/extcompat/code/consent.py +162 -0
  90. src/extcompat/code/host.py +353 -0
  91. src/extcompat/code/hosts/py_host.py +763 -0
  92. src/extcompat/code/locate.py +105 -0
  93. src/extcompat/code/manager.py +325 -0
  94. src/extcompat/code/permissions.py +154 -0
  95. src/extcompat/code/sandbox.py +60 -0
  96. src/extcompat/colors.py +131 -0
  97. src/extcompat/common.py +184 -0
  98. src/extcompat/cson.py +269 -0
  99. src/extcompat/formats/__init__.py +22 -0
  100. src/extcompat/formats/_tm.py +189 -0
  101. src/extcompat/formats/_util.py +31 -0
  102. src/extcompat/formats/base16.py +66 -0
  103. src/extcompat/formats/brackets.py +172 -0
  104. src/extcompat/formats/eclipse.py +193 -0
  105. src/extcompat/formats/emacs.py +361 -0
  106. src/extcompat/formats/geany.py +147 -0
  107. src/extcompat/formats/generic.py +184 -0
  108. src/extcompat/formats/gtksource.py +117 -0
  109. src/extcompat/formats/helix.py +91 -0
  110. src/extcompat/formats/jetbrains.py +343 -0
  111. src/extcompat/formats/kate.py +130 -0
  112. src/extcompat/formats/micro.py +131 -0
  113. src/extcompat/formats/nano.py +111 -0
  114. src/extcompat/formats/notepadpp.py +140 -0
  115. src/extcompat/formats/pulsar.py +165 -0
  116. src/extcompat/formats/pyides.py +163 -0
  117. src/extcompat/formats/sublime.py +340 -0
  118. src/extcompat/jsonc.py +65 -0
  119. src/extcompat/lessish.py +128 -0
  120. src/extcompat/manager.py +122 -0
  121. src/extcompat/market/__init__.py +63 -0
  122. src/extcompat/market/sources.py +211 -0
  123. src/extcompat/model.py +88 -0
  124. src/extcompat/net.py +228 -0
  125. src/extcompat/openvsx.py +63 -0
  126. src/extcompat/readers.py +362 -0
  127. src/extcompat/registry.py +73 -0
  128. src/extcompat/safexml.py +63 -0
  129. src/extcompat/sexp.py +187 -0
  130. src/extcompat/sources.py +105 -0
  131. src/extcompat/store.py +276 -0
  132. src/extcompat/textmate.py +214 -0
  133. src/extcompat/themes.py +487 -0
  134. src/extcompat/yamlite.py +294 -0
  135. src/fileio.py +94 -0
  136. src/fs_ops.py +106 -0
  137. src/i18n.py +233 -0
  138. src/ia/__init__.py +1 -0
  139. src/ia/actions.py +295 -0
  140. src/ia/approval_gate.py +672 -0
  141. src/ia/checkpoints.py +308 -0
  142. src/ia/context_builder.py +921 -0
  143. src/ia/dialdiff.py +408 -0
  144. src/ia/iaspace.py +2078 -0
  145. src/ia/pair.py +296 -0
  146. src/ia/providers.py +954 -0
  147. src/ia/session.py +335 -0
  148. src/ia/toolbox.py +2524 -0
  149. src/launcher_actions.py +204 -0
  150. src/lint/__init__.py +1 -0
  151. src/lint/manager.py +1058 -0
  152. src/locales/.translate_manifest.json +64170 -0
  153. src/locales/de.json +4936 -0
  154. src/locales/en.json +4936 -0
  155. src/locales/es.json +4936 -0
  156. src/locales/fr.json +4936 -0
  157. src/locales/it.json +4936 -0
  158. src/locales/ja.json +4936 -0
  159. src/locales/ko.json +4936 -0
  160. src/locales/nl.json +4936 -0
  161. src/locales/pl.json +4936 -0
  162. src/locales/pt-BR.json +4936 -0
  163. src/locales/ru.json +4936 -0
  164. src/locales/tr.json +4936 -0
  165. src/locales/uk.json +4936 -0
  166. src/locales/zh-CN.json +4936 -0
  167. src/lsp/__init__.py +26 -0
  168. src/lsp/client.py +2300 -0
  169. src/lsp/dap_client.py +480 -0
  170. src/lsp/edits.py +84 -0
  171. src/lsp/framing.py +73 -0
  172. src/lsp/protocol.py +931 -0
  173. src/main.py +260 -0
  174. src/memtrim.py +91 -0
  175. src/plugins/__init__.py +1 -0
  176. src/plugins/api.py +1761 -0
  177. src/plugins/loader.py +571 -0
  178. src/plugins/process_runner.py +519 -0
  179. src/plugins/registry.py +342 -0
  180. src/plugins/safety.py +367 -0
  181. src/plugins/startup.py +195 -0
  182. src/plugins/store.py +1178 -0
  183. src/proc_registry.py +278 -0
  184. src/pyexec.py +394 -0
  185. src/recovery.py +259 -0
  186. src/stall_trace.py +92 -0
  187. src/standalone.py +1070 -0
  188. src/startup_profile.py +35 -0
  189. src/syntax/__init__.py +1 -0
  190. src/syntax/highlighter.py +776 -0
  191. src/syntax/patterns.py +584 -0
  192. src/system_profile.py +430 -0
  193. src/terminal/backends.py +658 -0
  194. src/terminal/internal.py +346 -0
  195. src/terminal/keys.py +138 -0
  196. src/terminal/palette.py +67 -0
  197. src/terminal/session.py +283 -0
  198. src/terminal/shells.py +79 -0
  199. src/terminal/view.py +489 -0
  200. src/terminal/vt.py +870 -0
  201. src/textfmt.py +22 -0
  202. src/theme/__init__.py +1 -0
  203. src/theme/base.py +1281 -0
  204. src/theme/colors.py +49 -0
  205. src/theme/manager.py +602 -0
  206. src/theme/utils.py +312 -0
  207. src/toolbox.py +329 -0
  208. src/trash_core.py +531 -0
  209. src/ui/__init__.py +1 -0
  210. src/ui/_perf_utils.py +285 -0
  211. src/ui/_persistence_utils.py +93 -0
  212. src/ui/accessibility.py +843 -0
  213. src/ui/activity_bar.py +860 -0
  214. src/ui/app_embed.py +434 -0
  215. src/ui/archive_panel.py +608 -0
  216. src/ui/bookmarks.py +314 -0
  217. src/ui/breadcrumb.py +383 -0
  218. src/ui/calculator_panel.py +982 -0
  219. src/ui/calendar_panel.py +1218 -0
  220. src/ui/chat_panel.py +1271 -0
  221. src/ui/chat_profile_dialog.py +278 -0
  222. src/ui/chat_render.py +128 -0
  223. src/ui/clock_panel.py +810 -0
  224. src/ui/code_outline.py +364 -0
  225. src/ui/code_runner.py +729 -0
  226. src/ui/code_stats.py +546 -0
  227. src/ui/collab_panel.py +1009 -0
  228. src/ui/color_picker.py +547 -0
  229. src/ui/command_palette.py +452 -0
  230. src/ui/cursor_manager.py +750 -0
  231. src/ui/custom_keywords_panel.py +413 -0
  232. src/ui/debug_panel.py +1037 -0
  233. src/ui/dependency_graph.py +692 -0
  234. src/ui/diff_panel.py +381 -0
  235. src/ui/docs_panel.py +514 -0
  236. src/ui/doom_embed.py +349 -0
  237. src/ui/dropdown.py +321 -0
  238. src/ui/easter_eggs.py +979 -0
  239. src/ui/env_manager.py +666 -0
  240. src/ui/extcode_bridge.py +215 -0
  241. src/ui/extcode_dialogs.py +412 -0
  242. src/ui/extcompat_dialog.py +583 -0
  243. src/ui/file_timeline.py +319 -0
  244. src/ui/file_tree.py +1208 -0
  245. src/ui/find_in_files.py +1355 -0
  246. src/ui/flowchart_panel.py +727 -0
  247. src/ui/formatter_panel.py +490 -0
  248. src/ui/git_auth.py +763 -0
  249. src/ui/git_clone_dialog.py +487 -0
  250. src/ui/git_panel.py +1483 -0
  251. src/ui/grab_safe.py +84 -0
  252. src/ui/internal_python_dialog.py +98 -0
  253. src/ui/k_ui/__init__.py +1305 -0
  254. src/ui/k_ui/_bgrenderer.py +317 -0
  255. src/ui/k_ui/_colors.py +213 -0
  256. src/ui/k_ui/_dock.py +545 -0
  257. src/ui/k_ui/_easter.py +290 -0
  258. src/ui/k_ui/_engine.py +5448 -0
  259. src/ui/k_ui/_perf.py +333 -0
  260. src/ui/k_ui/_tkutil.py +7 -0
  261. src/ui/k_ui/_tooltip.py +365 -0
  262. src/ui/k_ui/_widgets.py +1204 -0
  263. src/ui/k_ui/_world.py +837 -0
  264. src/ui/key_remapper.py +856 -0
  265. src/ui/launcher.py +1252 -0
  266. src/ui/lazy_panel.py +73 -0
  267. src/ui/macro_recorder.py +610 -0
  268. src/ui/menu_bar.py +898 -0
  269. src/ui/output_panel.py +321 -0
  270. src/ui/paint_canvas.py +1000 -0
  271. src/ui/paint_engine.py +535 -0
  272. src/ui/paint_panel.py +888 -0
  273. src/ui/panel_detach.py +112 -0
  274. src/ui/performance_panel.py +861 -0
  275. src/ui/pip_manager.py +1758 -0
  276. src/ui/plugin_panel.py +1586 -0
  277. src/ui/pomodoro_panel.py +447 -0
  278. src/ui/problems.py +566 -0
  279. src/ui/process_manager.py +1657 -0
  280. src/ui/project_templates.py +775 -0
  281. src/ui/recovery_dialog.py +122 -0
  282. src/ui/regex_playground.py +304 -0
  283. src/ui/remote_adapters.py +1398 -0
  284. src/ui/remote_browser.py +1224 -0
  285. src/ui/remote_profile_dialog.py +342 -0
  286. src/ui/render_panel.py +1293 -0
  287. src/ui/rest_client.py +549 -0
  288. src/ui/scratchpad.py +548 -0
  289. src/ui/search_bar.py +1274 -0
  290. src/ui/settings_editor.py +3349 -0
  291. src/ui/settings_window.py +1554 -0
  292. src/ui/snippets_panel.py +597 -0
  293. src/ui/sql_studio.py +1815 -0
  294. src/ui/status_bar.py +438 -0
  295. src/ui/tab_bar.py +654 -0
  296. src/ui/task_manager.py +1773 -0
  297. src/ui/terminal.py +525 -0
  298. src/ui/theme_preview_panel.py +851 -0
  299. src/ui/thread_safe_tk.py +152 -0
  300. src/ui/time_tracker.py +574 -0
  301. src/ui/tkbind.py +43 -0
  302. src/ui/todo_panel.py +358 -0
  303. src/ui/toolbox_panels.py +658 -0
  304. src/ui/trash_manager.py +657 -0
  305. src/ui/ui_scale.py +294 -0
  306. src/ui/ux_enhancements.py +41 -0
  307. src/ui/web_preview.py +397 -0
  308. src/ui/webdev.py +630 -0
  309. src/ui/welcome.py +567 -0
  310. src/ui/window_embed.py +1500 -0
  311. src/ui/wizard.py +1550 -0
  312. src/ui/workspace_switcher.py +418 -0
  313. src/ui/workspace_trust.py +370 -0
  314. src/ui/zen_audio.py +354 -0
  315. src/ui/zen_media.py +2271 -0
  316. src/ui/zen_media_client.py +303 -0
  317. src/ui/zen_media_host.py +329 -0
  318. src/ui/zen_player.py +907 -0
  319. src/ui/zen_player_widgets.py +700 -0
  320. src/updater/__init__.py +11 -0
  321. src/updater/assets.py +145 -0
  322. src/updater/backup.py +101 -0
  323. src/updater/channel.py +221 -0
  324. src/updater/dialog.py +492 -0
  325. src/updater/integrity.py +111 -0
  326. src/updater/manager.py +727 -0
  327. src/updater/result.py +114 -0
  328. src/venv_runtime.py +531 -0
  329. src/workspace_state.py +25 -0
src/ia/providers.py ADDED
@@ -0,0 +1,954 @@
1
+ """Codis IA - Provedores de modelos de linguagem.
2
+
3
+ Cada provedor implementa a interface BaseProvider:
4
+ - name / icon / description - metadados de exibição
5
+ - configure(cfg) - recebe dict de configuração
6
+ - send(messages, on_chunk, on_done, on_error) - streaming assíncrono
7
+ - cancel() - aborta a requisição em curso
8
+ - check() -> str|None - testa conectividade (None = OK)
9
+
10
+ Provedores disponíveis
11
+ ----------------------
12
+ AnthropicProvider - Claude (API Anthropic)
13
+ OpenAIProvider - ChatGPT / GPT (API OpenAI)
14
+ OpenAICompatibleProvider - Qualquer servidor /v1/chat/completions
15
+ (LM Studio, Jan, Groq, Together AI, OpenRouter...)
16
+ GeminiProvider - Google Gemini
17
+ OllamaProvider - Ollama via HTTP (localhost:11434)
18
+ LocalLibProvider - llama-cpp-python direto (execução local pesada)
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import contextlib
24
+ import json
25
+ import logging
26
+ import threading
27
+ import urllib.error
28
+ import urllib.request
29
+ from abc import ABC, abstractmethod
30
+ from collections.abc import Callable
31
+ from typing import Any
32
+
33
+ from src import proc_registry
34
+
35
+ logger = logging.getLogger("Codis.IA")
36
+
37
+ _OnChunk = Callable[[str], None]
38
+ _OnDone = Callable[[str], None]
39
+ _OnError = Callable[[str], None]
40
+
41
+
42
+ class BaseProvider(ABC):
43
+ """Classe base abstrata para todos os providers de IA do Codis."""
44
+
45
+ name: str = ""
46
+ icon: str = "[AI]"
47
+ description: str = ""
48
+ requires_key: bool = True
49
+
50
+ def __init__(self) -> None:
51
+ self._cfg: dict[str, Any] = {}
52
+ self._cancelled: threading.Event = threading.Event()
53
+
54
+ def configure(self, cfg: dict[str, Any]) -> None:
55
+ """Configura o provider com credenciais e parâmetros."""
56
+ self._cfg = cfg
57
+
58
+ def cancel(self) -> None:
59
+ """Cancela a requisição de IA em andamento, se houver."""
60
+ self._cancelled.set()
61
+
62
+ def _reset_cancel(self) -> None:
63
+ """Começa uma nova requisição com um evento de cancelamento **novo**.
64
+
65
+ Reutilizar (``clear``) o mesmo evento deixava a thread de uma requisição
66
+ cancelada voltar a rodar quando uma nova era enviada logo em seguida.
67
+ """
68
+ self._cancelled = threading.Event()
69
+
70
+ def _snapshot(self, options: dict[str, Any] | None = None) -> dict[str, Any]:
71
+ """Config efetiva *desta* requisição (cópia: imune a ``configure`` posterior)."""
72
+ cfg = dict(self._cfg)
73
+ if options:
74
+ cfg.update(options)
75
+ return cfg
76
+
77
+ def _spawn(self, worker: Callable[[], None], name: str) -> None:
78
+ """Roda ``worker`` numa thread daemon (o pedido ao modelo nunca bloqueia a interface).
79
+
80
+ O pedido fica no registro de tarefas como ``ia``, cancelável pelo Gerenciador de
81
+ Processos, até a thread terminar.
82
+ """
83
+ task = proc_registry.track_task("ia", name, self.cancel)
84
+
85
+ def _run() -> None:
86
+ try:
87
+ worker()
88
+ finally:
89
+ task.done()
90
+
91
+ threading.Thread(target=_run, daemon=True, name=name).start()
92
+
93
+ @abstractmethod
94
+ def send(
95
+ self,
96
+ messages: list[dict[str, Any]],
97
+ on_chunk: _OnChunk,
98
+ on_done: _OnDone,
99
+ on_error: _OnError,
100
+ options: dict[str, Any] | None = None,
101
+ ) -> None:
102
+ """Envia mensagens ao modelo em background thread.
103
+
104
+ ``options`` sobrepõe a config só desta requisição (system prompt,
105
+ ferramentas, callbacks) sem mexer no estado compartilhado do provedor.
106
+ """
107
+
108
+ def check(self, model_id: str = "") -> str | None:
109
+ """Testa conectividade e credenciais. Retorna None se OK."""
110
+ return None
111
+
112
+
113
+ def _post_stream(
114
+ url: str,
115
+ payload: dict,
116
+ headers: dict[str, str],
117
+ on_line: Callable[[bytes], None],
118
+ cancelled: threading.Event,
119
+ timeout: int = 120,
120
+ ) -> None:
121
+ """POST com streaming SSE/NDJSON."""
122
+ data = json.dumps(payload).encode("utf-8")
123
+ req = urllib.request.Request(
124
+ url, data=data, headers=headers, method="POST")
125
+ try:
126
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
127
+ for line in resp:
128
+ if cancelled.is_set():
129
+ break
130
+ if line.strip():
131
+ on_line(line)
132
+ except urllib.error.HTTPError as exc:
133
+ body = exc.read().decode("utf-8", errors="replace")
134
+ raise RuntimeError(f"HTTP {exc.code}: {body}") from exc
135
+
136
+
137
+ def _post_json(
138
+ url: str,
139
+ payload: dict,
140
+ headers: dict[str, str],
141
+ timeout: int = 60,
142
+ ) -> dict:
143
+ """POST que retorna JSON completo."""
144
+ data = json.dumps(payload).encode("utf-8")
145
+ req = urllib.request.Request(
146
+ url, data=data, headers=headers, method="POST")
147
+ try:
148
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
149
+ return json.loads(resp.read().decode("utf-8"))
150
+ except urllib.error.HTTPError as exc:
151
+ body = exc.read().decode("utf-8", errors="replace")
152
+ raise RuntimeError(f"HTTP {exc.code}: {body}") from exc
153
+
154
+
155
+ def _sse_text(raw: bytes) -> str:
156
+ """Texto de uma linha de streaming, sem o prefixo ``data:`` (vazio para ``[DONE]``)."""
157
+ text = raw.decode("utf-8", errors="replace").strip()
158
+ if text.startswith("data:"):
159
+ text = text[5:].strip()
160
+ return "" if text == "[DONE]" else text
161
+
162
+
163
+ def _anthropic_line_handler(
164
+ accumulated: list[str],
165
+ on_chunk: Callable[[str], None],
166
+ event_buffer: list[dict],
167
+ block_map: dict[int, dict],
168
+ ) -> Callable[[bytes], None]:
169
+ """Cria o tratador de linhas SSE da API de mensagens da Anthropic.
170
+
171
+ O texto recebido vai para ``accumulated``/``on_chunk``; os eventos ficam em
172
+ ``event_buffer`` e os blocos (inclusive o JSON parcial de ``tool_use``) em ``block_map``.
173
+ """
174
+
175
+ def on_line(raw: bytes) -> None:
176
+ text = _sse_text(raw)
177
+ if not text:
178
+ return
179
+ with contextlib.suppress(json.JSONDecodeError, KeyError):
180
+ event = json.loads(text)
181
+ ev_type = event.get("type", "")
182
+ if ev_type == "content_block_start":
183
+ block_map[event.get("index", 0)] = event.get("content_block", {})
184
+ elif ev_type == "content_block_delta":
185
+ idx = event.get("index", 0)
186
+ delta = event.get("delta", {})
187
+ if delta.get("type") == "text_delta":
188
+ chunk = delta.get("text", "")
189
+ if chunk:
190
+ accumulated.append(chunk)
191
+ on_chunk(chunk)
192
+ elif delta.get("type") == "input_json_delta":
193
+ block = block_map.setdefault(idx, {})
194
+ block["_json_acc"] = block.get("_json_acc", "") + delta.get("partial_json", "")
195
+ event_buffer.append(event)
196
+
197
+ return on_line
198
+
199
+
200
+ def _openai_line_handler(
201
+ accumulated: list[str],
202
+ on_chunk: Callable[[str], None],
203
+ finish_reason: list[str],
204
+ tool_calls_acc: dict[int, dict],
205
+ ) -> Callable[[bytes], None]:
206
+ """Cria o tratador de linhas SSE das APIs no formato OpenAI (chat completions).
207
+
208
+ ``finish_reason[0]`` recebe o motivo de término e ``tool_calls_acc`` acumula, por
209
+ índice, o id, o nome e os argumentos (em pedaços) de cada chamada de ferramenta.
210
+ """
211
+
212
+ def on_line(raw: bytes) -> None:
213
+ text = _sse_text(raw)
214
+ if not text:
215
+ return
216
+ with contextlib.suppress(json.JSONDecodeError, IndexError, KeyError):
217
+ event = json.loads(text)
218
+ choice = event.get("choices", [{}])[0]
219
+ delta = choice.get("delta", {})
220
+ if reason := choice.get("finish_reason"):
221
+ finish_reason[0] = reason
222
+ if chunk := delta.get("content", ""):
223
+ accumulated.append(chunk)
224
+ on_chunk(chunk)
225
+ for call in delta.get("tool_calls", []):
226
+ entry = tool_calls_acc.setdefault(
227
+ call.get("index", 0), {"id": "", "name": "", "args": ""}
228
+ )
229
+ entry["id"] += call.get("id", "")
230
+ function = call.get("function", {})
231
+ entry["name"] += function.get("name", "")
232
+ entry["args"] += function.get("arguments", "")
233
+
234
+ return on_line
235
+
236
+
237
+ def _ollama_line_handler(
238
+ accumulated: list[str],
239
+ on_chunk: Callable[[str], None],
240
+ done_reason: list[str],
241
+ tool_calls: list[dict],
242
+ ) -> Callable[[bytes], None]:
243
+ """Cria o tratador de linhas (JSON por linha) da API de chat do Ollama."""
244
+
245
+ def on_line(raw: bytes) -> None:
246
+ text = raw.decode("utf-8", errors="replace").strip()
247
+ if not text:
248
+ return
249
+ with contextlib.suppress(json.JSONDecodeError, KeyError):
250
+ event = json.loads(text)
251
+ message = event.get("message", {})
252
+ if chunk := message.get("content", ""):
253
+ accumulated.append(chunk)
254
+ on_chunk(chunk)
255
+ if event.get("done"):
256
+ done_reason[0] = event.get("done_reason", "stop")
257
+ tool_calls.extend(message.get("tool_calls", []))
258
+
259
+ return on_line
260
+
261
+
262
+ def _gemini_line_handler(
263
+ accumulated: list[str], on_chunk: Callable[[str], None]
264
+ ) -> Callable[[bytes], None]:
265
+ """Cria o tratador de linhas SSE do ``streamGenerateContent`` do Gemini."""
266
+
267
+ def on_line(raw: bytes) -> None:
268
+ text = _sse_text(raw)
269
+ if not text:
270
+ return
271
+ with contextlib.suppress(json.JSONDecodeError, IndexError, KeyError):
272
+ event = json.loads(text)
273
+ parts = event.get("candidates", [{}])[0].get("content", {}).get("parts", [{}])
274
+ if chunk := parts[0].get("text", ""):
275
+ accumulated.append(chunk)
276
+ on_chunk(chunk)
277
+
278
+ return on_line
279
+
280
+
281
+ _MAX_TOOL_ROUNDS = 20
282
+
283
+
284
+ def _with_tool_results(
285
+ messages: list[dict],
286
+ calls: dict[int, dict],
287
+ on_tool_call: Callable[[str, dict], Any],
288
+ ) -> list[dict]:
289
+ """Acrescenta à conversa a mensagem do assistente com as chamadas e o resultado de cada uma.
290
+
291
+ ``calls`` é o acumulado por índice de :func:`_openai_line_handler`; os argumentos
292
+ chegam como texto JSON e, se estiverem malformados, a ferramenta recebe ``{}``.
293
+ """
294
+ tool_calls = [
295
+ {
296
+ "id": calls[i]["id"],
297
+ "type": "function",
298
+ "function": {"name": calls[i]["name"], "arguments": calls[i]["args"]},
299
+ }
300
+ for i in sorted(calls)
301
+ ]
302
+ updated = [*messages, {"role": "assistant", "content": None, "tool_calls": tool_calls}]
303
+ for call in tool_calls:
304
+ function = call["function"]
305
+ try:
306
+ args = json.loads(function.get("arguments", "{}") or "{}")
307
+ except json.JSONDecodeError:
308
+ args = {}
309
+ result = on_tool_call(function["name"], args)
310
+ updated.append({"role": "tool", "tool_call_id": call["id"], "content": str(result)})
311
+ return updated
312
+
313
+
314
+ def _openai_chat_loop(
315
+ url: str,
316
+ headers: dict[str, str],
317
+ request: dict[str, Any],
318
+ messages: list[dict],
319
+ on_chunk: Callable[[str], None],
320
+ on_error: Callable[[str], None],
321
+ cancelled: threading.Event,
322
+ on_tool_call: Callable[[str, dict], Any] | None = None,
323
+ tools_schema: list[dict] | None = None,
324
+ describe_error: Callable[[Exception], str] = str,
325
+ ) -> str | None:
326
+ """Conversa com uma API no formato OpenAI, repetindo enquanto o modelo pedir ferramentas.
327
+
328
+ Args:
329
+ request: Campos fixos do pedido (``model``, ``max_tokens``...); ``messages`` e
330
+ ``stream`` são acrescentados a cada rodada.
331
+ describe_error: Texto enviado a ``on_error`` quando a conexão falha.
332
+
333
+ Returns:
334
+ O texto completo da resposta, ou ``None`` se houve erro (já informado) ou o
335
+ pedido foi cancelado antes de começar.
336
+ """
337
+ accumulated: list[str] = []
338
+ current = list(messages)
339
+ for _ in range(_MAX_TOOL_ROUNDS):
340
+ if cancelled.is_set():
341
+ break
342
+ payload = {**request, "messages": current, "stream": True}
343
+ if tools_schema and on_tool_call:
344
+ payload["tools"] = tools_schema
345
+ payload["tool_choice"] = "auto"
346
+ finish_reason: list[str] = [""]
347
+ calls: dict[int, dict] = {}
348
+ handler = _openai_line_handler(accumulated, on_chunk, finish_reason, calls)
349
+ try:
350
+ _post_stream(url, payload, headers, handler, cancelled)
351
+ except (RuntimeError, OSError) as exc:
352
+ on_error(describe_error(exc))
353
+ return None
354
+ if finish_reason[0] != "tool_calls" or not on_tool_call or not calls:
355
+ break
356
+ current = _with_tool_results(current, calls, on_tool_call)
357
+ return "".join(accumulated)
358
+
359
+
360
+ class AnthropicProvider(BaseProvider):
361
+ name = "Anthropic (Claude)"
362
+ icon = "✳"
363
+ description = "Claude models by Anthropic. Requires an API key from anthropic.com."
364
+ _API_URL = "https://api.anthropic.com/v1/messages"
365
+ _API_VERSION = "2023-06-01"
366
+ _DEFAULT_MODEL = "claude-sonnet-5-5"
367
+
368
+ def send(self, messages, on_chunk, on_done, on_error, options=None) -> None:
369
+ """Envia uma mensagem para a API Anthropic e retorna a resposta."""
370
+ self._reset_cancel()
371
+ cfg = self._snapshot(options)
372
+ cancelled = self._cancelled
373
+
374
+ def _worker() -> None:
375
+ api_key = cfg.get("chave_api", "")
376
+ model_id = cfg.get("modelo", self._DEFAULT_MODEL)
377
+ max_tok = int(cfg.get("max_tokens", 4096))
378
+ system_prompt = cfg.get("sistema", "")
379
+ tools_schema = cfg.get("_ferramentas")
380
+ on_tool_call = cfg.get("_on_tool_call")
381
+ if not api_key:
382
+ on_error("Anthropic API key not configured.")
383
+ return
384
+ headers = {
385
+ "Content-Type": "application/json",
386
+ "x-api-key": api_key,
387
+ "anthropic-version": self._API_VERSION,
388
+ }
389
+
390
+ anthropic_tools: list[dict] | None = None
391
+ if tools_schema and on_tool_call:
392
+ anthropic_tools = []
393
+ for t in tools_schema:
394
+ fn = t.get("function", t)
395
+ anthropic_tools.append(
396
+ {
397
+ "name": fn["name"],
398
+ "description": fn.get("description", ""),
399
+ "input_schema": fn.get(
400
+ "parameters", {
401
+ "type": "object", "properties": {}}
402
+ ),
403
+ }
404
+ )
405
+
406
+ current_messages = list(messages)
407
+ accumulated: list[str] = []
408
+
409
+ for _loop in range(20):
410
+ if cancelled.is_set():
411
+ break
412
+ payload: dict[str, Any] = {
413
+ "model": model_id,
414
+ "max_tokens": max_tok,
415
+ "stream": True,
416
+ "messages": current_messages,
417
+ }
418
+ if system_prompt:
419
+ payload["system"] = system_prompt
420
+ if anthropic_tools:
421
+ payload["tools"] = anthropic_tools
422
+
423
+ event_buffer: list[dict] = []
424
+ block_map: dict[int, dict] = {}
425
+
426
+ try:
427
+ _on_line = _anthropic_line_handler(accumulated, on_chunk, event_buffer, block_map)
428
+ _post_stream(
429
+ self._API_URL, payload, headers, _on_line, cancelled
430
+ )
431
+ except (RuntimeError, OSError) as exc:
432
+ on_error(str(exc))
433
+ return
434
+
435
+ stop_reason = None
436
+ for ev in reversed(event_buffer):
437
+ if ev.get("type") == "message_delta":
438
+ stop_reason = ev.get("delta", {}).get("stop_reason")
439
+ break
440
+
441
+ if stop_reason != "tool_use" or not on_tool_call:
442
+ break
443
+
444
+ tool_use_blocks = [
445
+ b for b in block_map.values() if b.get("type") == "tool_use"
446
+ ]
447
+ if not tool_use_blocks:
448
+ break
449
+
450
+ assistant_content: list[dict] = []
451
+ for blk in sorted(block_map.items()):
452
+ b = blk[1]
453
+ if b.get("type") == "text" and b.get("text"):
454
+ assistant_content.append(
455
+ {"type": "text", "text": b["text"]})
456
+ elif b.get("type") == "tool_use":
457
+ try:
458
+ inp = json.loads(b.get("_json_acc", "{}") or "{}")
459
+ except json.JSONDecodeError:
460
+ inp = {}
461
+ assistant_content.append(
462
+ {
463
+ "type": "tool_use",
464
+ "id": b.get("id", ""),
465
+ "name": b.get("name", ""),
466
+ "input": inp,
467
+ }
468
+ )
469
+
470
+ current_messages = list(current_messages)
471
+ current_messages.append(
472
+ {"role": "assistant", "content": assistant_content}
473
+ )
474
+
475
+ tool_results: list[dict] = []
476
+ for blk in tool_use_blocks:
477
+ try:
478
+ inp = json.loads(blk.get("_json_acc", "{}") or "{}")
479
+ except json.JSONDecodeError:
480
+ inp = {}
481
+ result = on_tool_call(blk.get("name", ""), inp)
482
+ tool_results.append(
483
+ {
484
+ "type": "tool_result",
485
+ "tool_use_id": blk.get("id", ""),
486
+ "content": str(result),
487
+ }
488
+ )
489
+ current_messages.append(
490
+ {"role": "user", "content": tool_results})
491
+
492
+ on_done("".join(accumulated))
493
+
494
+ self._spawn(_worker, "ia-anthropic")
495
+
496
+ def check(self, model_id: str = "") -> str | None:
497
+ """Verifica se as credenciais Anthropic estão válidas e acessíveis."""
498
+ api_key = self._cfg.get("chave_api", "")
499
+ if not api_key:
500
+ return "API key not configured."
501
+ try:
502
+ _post_json(
503
+ self._API_URL,
504
+ {
505
+ "model": self._DEFAULT_MODEL,
506
+ "max_tokens": 1,
507
+ "messages": [{"role": "user", "content": "ping"}],
508
+ },
509
+ {
510
+ "Content-Type": "application/json",
511
+ "x-api-key": api_key,
512
+ "anthropic-version": self._API_VERSION,
513
+ },
514
+ timeout=10,
515
+ )
516
+ return None
517
+ except RuntimeError as exc:
518
+ return str(exc)
519
+
520
+
521
+ class OpenAIProvider(BaseProvider):
522
+ name = "OpenAI (ChatGPT)"
523
+ icon = "🟢"
524
+ description = "GPT models by OpenAI. Requires an API key from platform.openai.com."
525
+ _DEFAULT_URL = "https://api.openai.com/v1/chat/completions"
526
+ _DEFAULT_MODEL = "gpt-5.6-terra"
527
+
528
+ def send(self, messages, on_chunk, on_done, on_error, options=None) -> None:
529
+ """Envia uma mensagem para a API OpenAI e retorna a resposta."""
530
+ self._reset_cancel()
531
+ cfg = self._snapshot(options)
532
+ cancelled = self._cancelled
533
+
534
+ def _worker() -> None:
535
+ api_key = cfg.get("chave_api", "")
536
+ model_id = cfg.get("modelo", self._DEFAULT_MODEL)
537
+ max_tok = int(cfg.get("max_tokens", 4096))
538
+ url = cfg.get("url_base", self._DEFAULT_URL)
539
+ system_prompt = cfg.get("sistema", "")
540
+ tools_schema = cfg.get("_ferramentas")
541
+ on_tool_call = cfg.get("_on_tool_call")
542
+ if not api_key:
543
+ on_error("OpenAI API key not configured.")
544
+ return
545
+ headers = {
546
+ "Content-Type": "application/json",
547
+ "Authorization": f"Bearer {api_key}",
548
+ }
549
+ conversation = [{"role": "system", "content": system_prompt}] if system_prompt else []
550
+ conversation.extend(messages)
551
+ text = _openai_chat_loop(
552
+ url,
553
+ headers,
554
+ {"model": model_id, "max_completion_tokens": max_tok},
555
+ conversation,
556
+ on_chunk,
557
+ on_error,
558
+ cancelled,
559
+ on_tool_call,
560
+ tools_schema,
561
+ )
562
+ if text is not None:
563
+ on_done(text)
564
+
565
+ self._spawn(_worker, "ia-openai")
566
+
567
+ def check(self, model_id: str = "") -> str | None:
568
+ """Verifica se as credenciais OpenAI estão válidas e acessíveis."""
569
+ api_key = self._cfg.get("chave_api", "")
570
+ if not api_key:
571
+ return "API key not configured."
572
+ try:
573
+ _post_json(
574
+ self._cfg.get("url_base", self._DEFAULT_URL),
575
+ {
576
+ "model": self._cfg.get("modelo", self._DEFAULT_MODEL),
577
+ "max_completion_tokens": 16,
578
+ "stream": False,
579
+ "messages": [{"role": "user", "content": "ping"}],
580
+ },
581
+ {
582
+ "Content-Type": "application/json",
583
+ "Authorization": f"Bearer {api_key}",
584
+ },
585
+ timeout=10,
586
+ )
587
+ return None
588
+ except RuntimeError as exc:
589
+ return str(exc)
590
+
591
+
592
+ class OpenAICompatibleProvider(BaseProvider):
593
+ name = "OpenAI-Compatible (LM Studio / Groq / etc.)"
594
+ icon = "🔀"
595
+ description = (
596
+ "LM Studio, Jan, LocalAI, vLLM, Groq, Together AI, OpenRouter, Mistral, etc."
597
+ )
598
+ requires_key = False
599
+ _DEFAULT_URL = "http://localhost:1234/v1/chat/completions"
600
+ _DEFAULT_MODEL = ""
601
+
602
+ def send(self, messages, on_chunk, on_done, on_error, options=None) -> None:
603
+ """Envia uma mensagem para a API compatível com OpenAI e retorna a resposta."""
604
+ self._reset_cancel()
605
+ cfg = self._snapshot(options)
606
+ cancelled = self._cancelled
607
+
608
+ def _worker() -> None:
609
+ url = cfg.get("url", self._DEFAULT_URL)
610
+ model_id = cfg.get("modelo", self._DEFAULT_MODEL)
611
+ max_tok = int(cfg.get("max_tokens", 4096))
612
+ api_key = cfg.get("chave_api", "")
613
+ system_prompt = cfg.get("sistema", "")
614
+ tools_schema = cfg.get("_ferramentas")
615
+ on_tool_call = cfg.get("_on_tool_call")
616
+
617
+ conversation = [{"role": "system", "content": system_prompt}] if system_prompt else []
618
+ conversation.extend(messages)
619
+ headers: dict[str, str] = {"Content-Type": "application/json"}
620
+ if api_key:
621
+ headers["Authorization"] = f"Bearer {api_key}"
622
+ request: dict[str, Any] = {"max_tokens": max_tok}
623
+ if model_id:
624
+ request["model"] = model_id
625
+ text = _openai_chat_loop(
626
+ url,
627
+ headers,
628
+ request,
629
+ conversation,
630
+ on_chunk,
631
+ on_error,
632
+ cancelled,
633
+ on_tool_call,
634
+ tools_schema,
635
+ describe_error=lambda exc: (
636
+ f"Server not reachable at {url}\n\n"
637
+ f"Check if the server is running.\n\nError: {exc}"
638
+ ),
639
+ )
640
+ if text is not None:
641
+ on_done(text)
642
+
643
+ self._spawn(_worker, "ia-compat-openai")
644
+
645
+ def check(self, model_id: str = "") -> str | None:
646
+ """Verifica se o endpoint compatível com OpenAI está acessível."""
647
+ url_chat = self._cfg.get("url", self._DEFAULT_URL)
648
+ base = url_chat.split("/chat/completions")[0].split("/completions")[0]
649
+ if not base.endswith("/v1"):
650
+ base = base.rstrip("/") + "/v1"
651
+ models_url = base + "/models"
652
+ api_key = self._cfg.get("chave_api", "")
653
+ try:
654
+ req_headers: dict[str, str] = {}
655
+ if api_key:
656
+ req_headers["Authorization"] = f"Bearer {api_key}"
657
+ req = urllib.request.Request(models_url, headers=req_headers)
658
+ with urllib.request.urlopen(req, timeout=5) as resp:
659
+ data = json.loads(resp.read().decode("utf-8"))
660
+ models = [m.get("id", "") for m in data.get("data", [])]
661
+ if models:
662
+ return None
663
+ return "Server reachable but no models available."
664
+ except (OSError, urllib.error.URLError, json.JSONDecodeError) as exc:
665
+ return f"Server not reachable at {models_url}: {exc}"
666
+
667
+
668
+ class GeminiProvider(BaseProvider):
669
+ """Provedor para a API Google Gemini."""
670
+
671
+ name = "Google Gemini"
672
+ icon = "*"
673
+ description = (
674
+ "Gemini models by Google. Requires an API key from aistudio.google.com."
675
+ )
676
+
677
+ _URL_TEMPLATE = "https://generativelanguage.googleapis.com/v1beta/{model}:streamGenerateContent?alt=sse&key={key}"
678
+ _DEFAULT_MODEL = "models/gemini-3.8-flash"
679
+
680
+ def send(self, messages, on_chunk, on_done, on_error, options=None) -> None:
681
+ """Envia mensagens ao Google Gemini com streaming SSE."""
682
+ self._reset_cancel()
683
+ cfg = self._snapshot(options)
684
+ cancelled = self._cancelled
685
+
686
+ def _worker() -> None:
687
+ api_key = cfg.get("chave_api", "")
688
+ model_id = cfg.get("modelo", self._DEFAULT_MODEL)
689
+ if not api_key:
690
+ on_error("Gemini API key not configured.")
691
+ return
692
+
693
+ if not model_id.startswith(("models/", "tunedModels/")):
694
+ model_id = "models/" + model_id
695
+
696
+ gemini_contents = []
697
+ for msg in messages:
698
+ role = msg["role"]
699
+ if role == "system":
700
+ continue
701
+ gemini_role = "user" if role == "user" else "model"
702
+ gemini_contents.append(
703
+ {"role": gemini_role, "parts": [{"text": msg["content"]}]}
704
+ )
705
+
706
+ payload: dict[str, Any] = {
707
+ "contents": gemini_contents,
708
+ "generationConfig": {
709
+ "maxOutputTokens": int(cfg.get("max_tokens", 4096)),
710
+ },
711
+ }
712
+
713
+ system_prompt = cfg.get("sistema", "")
714
+ if system_prompt:
715
+ payload["system_instruction"] = {
716
+ "parts": [{"text": system_prompt}]}
717
+
718
+ url = self._URL_TEMPLATE.format(model=model_id, key=api_key)
719
+ headers = {"Content-Type": "application/json"}
720
+ accumulated: list[str] = []
721
+ try:
722
+ _post_stream(
723
+ url,
724
+ payload,
725
+ headers,
726
+ _gemini_line_handler(accumulated, on_chunk),
727
+ cancelled,
728
+ )
729
+ on_done("".join(accumulated))
730
+ except (RuntimeError, OSError) as exc:
731
+ on_error(str(exc))
732
+
733
+ self._spawn(_worker, "ia-gemini")
734
+
735
+ def check(self, model_id: str = "") -> str | None:
736
+ """Verifica se a chave de API do Gemini está configurada."""
737
+ api_key = self._cfg.get("chave_api", "")
738
+ return None if api_key else "Gemini API key not configured."
739
+
740
+
741
+ class OllamaProvider(BaseProvider):
742
+ name = "Ollama (local HTTP)"
743
+ icon = "🦙"
744
+ description = (
745
+ "Local models via Ollama. Install from ollama.com and run 'ollama serve'."
746
+ )
747
+ requires_key = False
748
+ _DEFAULT_URL = "http://localhost:11434/api/chat"
749
+ _MODELS_URL = "http://localhost:11434/api/tags"
750
+
751
+ def send(self, messages, on_chunk, on_done, on_error, options=None) -> None:
752
+ """Envia uma mensagem para o Ollama local e retorna a resposta."""
753
+ self._reset_cancel()
754
+ cfg = self._snapshot(options)
755
+ cancelled = self._cancelled
756
+
757
+ def _worker() -> None:
758
+ url = cfg.get("url", self._DEFAULT_URL)
759
+ model_id = cfg.get("modelo", "llama3")
760
+ tools_schema = cfg.get("_ferramentas")
761
+ on_tool_call = cfg.get("_on_tool_call")
762
+ current_messages = list(messages)
763
+ accumulated: list[str] = []
764
+
765
+ for _loop in range(20):
766
+ if cancelled.is_set():
767
+ break
768
+ payload: dict[str, Any] = {
769
+ "model": model_id,
770
+ "messages": current_messages,
771
+ "stream": True,
772
+ }
773
+ if tools_schema and on_tool_call:
774
+ payload["tools"] = tools_schema
775
+
776
+ headers = {"Content-Type": "application/json"}
777
+ tool_calls_buf: list[dict] = []
778
+ done_reason: list[str] = [""]
779
+ try:
780
+ _on_line = _ollama_line_handler(accumulated, on_chunk, done_reason, tool_calls_buf)
781
+ _post_stream(url, payload, headers,
782
+ _on_line, cancelled)
783
+ except (RuntimeError, OSError, ConnectionRefusedError) as exc:
784
+ on_error(f"Ollama not reachable: {exc}")
785
+ return
786
+
787
+ if not tool_calls_buf or not on_tool_call:
788
+ break
789
+
790
+ current_messages = list(current_messages)
791
+ current_messages.append(
792
+ {
793
+ "role": "assistant",
794
+ "content": "",
795
+ "tool_calls": tool_calls_buf,
796
+ }
797
+ )
798
+ for tc in tool_calls_buf:
799
+ fn_info = tc.get("function", {})
800
+ args = fn_info.get("arguments", {})
801
+ if isinstance(args, str):
802
+ try:
803
+ args = json.loads(args)
804
+ except json.JSONDecodeError:
805
+ args = {}
806
+ result = on_tool_call(fn_info.get("name", ""), args)
807
+ current_messages.append(
808
+ {
809
+ "role": "tool",
810
+ "content": str(result),
811
+ }
812
+ )
813
+
814
+ on_done("".join(accumulated))
815
+
816
+ self._spawn(_worker, "ia-ollama")
817
+
818
+ def list_models(self) -> list[str]:
819
+ """Lista os modelos disponíveis no servidor Ollama local."""
820
+ try:
821
+ req = urllib.request.Request(self._MODELS_URL, method="GET")
822
+ with urllib.request.urlopen(req, timeout=5) as resp:
823
+ data = json.loads(resp.read().decode("utf-8"))
824
+ return [m["name"] for m in data.get("models", [])]
825
+ except (OSError, urllib.error.URLError, json.JSONDecodeError):
826
+ return []
827
+
828
+ def check(self, model_id: str = "") -> str | None:
829
+ """Verifica se o servidor Ollama está em execução e acessível."""
830
+ models = self.list_models()
831
+ if not models:
832
+ return "Ollama server not reachable or no models installed."
833
+ return None
834
+
835
+
836
+ WARNING_LOCAL_LIB = """⚠ LOCAL LIBRARY EXECUTION MODE ... (mantido original)"""
837
+
838
+
839
+ class LocalLibProvider(BaseProvider):
840
+ name = "Local (llama-cpp-python)"
841
+ icon = "🖥"
842
+ description = "Loads a GGUF model directly in memory using llama-cpp-python."
843
+ requires_key = False
844
+ _loaded_model: Any = None
845
+ _model_path: str = ""
846
+ _load_lock: threading.Lock = threading.Lock()
847
+
848
+ def send(self, messages, on_chunk, on_done, on_error, options=None) -> None:
849
+ """Envia uma mensagem para o provider de biblioteca local e retorna a resposta."""
850
+ self._reset_cancel()
851
+ cfg = self._snapshot(options)
852
+ cancelled = self._cancelled
853
+
854
+ def _worker() -> None:
855
+ try:
856
+ from llama_cpp import Llama
857
+ except ImportError:
858
+ on_error(
859
+ "llama-cpp-python not installed.\nInstall with: pip install llama-cpp-python"
860
+ )
861
+ return
862
+
863
+ model_path = cfg.get("caminho_modelo", "")
864
+ if not model_path:
865
+ on_error("Path to .gguf file not configured.")
866
+ return
867
+
868
+ n_gpu = int(cfg.get("n_gpu_layers", 0))
869
+ ctx_size = int(cfg.get("n_ctx", 4096))
870
+ max_tok = int(cfg.get("max_tokens", 2048))
871
+
872
+ cls = self.__class__
873
+ with cls._load_lock:
874
+ if cls._loaded_model is None or cls._model_path != model_path:
875
+ try:
876
+ on_chunk("⏳ Carregando modelo (pode demorar)...\n")
877
+ cls._loaded_model = Llama(
878
+ model_path=model_path,
879
+ n_gpu_layers=n_gpu,
880
+ n_ctx=ctx_size,
881
+ verbose=False,
882
+ )
883
+ cls._model_path = model_path
884
+ on_chunk("✅ Modelo carregado.\n\n")
885
+ except (ValueError, RuntimeError, OSError) as exc:
886
+ on_error(f"Error loading model: {exc}")
887
+ return
888
+
889
+ model = cls._loaded_model
890
+
891
+ prompt_parts = []
892
+ for msg in messages:
893
+ role = msg["role"]
894
+ prompt_parts.append(
895
+ "<|im_start|>" + role + "\n" +
896
+ msg["content"] + "<|im_end|>"
897
+ )
898
+ prompt_parts.append("<|im_start|>assistant\n")
899
+ full_prompt = "\n".join(prompt_parts)
900
+
901
+ accumulated: list[str] = []
902
+ try:
903
+ output = model(
904
+ full_prompt,
905
+ max_tokens=max_tok,
906
+ stream=True,
907
+ stop=["<|im_end|>", "<|im_start|>"],
908
+ )
909
+ for chunk_data in output:
910
+ if cancelled.is_set():
911
+ break
912
+ chunk = chunk_data["choices"][0]["text"]
913
+ if chunk:
914
+ accumulated.append(chunk)
915
+ on_chunk(chunk)
916
+ on_done("".join(accumulated))
917
+ except (RuntimeError, ValueError) as exc:
918
+ on_error(f"Error during generation: {exc}")
919
+
920
+ self._spawn(_worker, "ia-local-lib")
921
+
922
+ def check(self, model_id: str = "") -> str | None:
923
+ """Verifica se a biblioteca de IA local está disponível."""
924
+ import importlib.util
925
+
926
+ if importlib.util.find_spec("llama_cpp") is None:
927
+ return "llama-cpp-python not installed (pip install llama-cpp-python)."
928
+ import os
929
+
930
+ model_path = self._cfg.get("caminho_modelo", "")
931
+ if not model_path:
932
+ return "Path to .gguf file not configured."
933
+ if not os.path.exists(model_path):
934
+ return f"File not found: {model_path}"
935
+ return None
936
+
937
+
938
+ PROVIDERS: list[type[BaseProvider]] = [
939
+ AnthropicProvider,
940
+ OpenAIProvider,
941
+ OpenAICompatibleProvider,
942
+ GeminiProvider,
943
+ OllamaProvider,
944
+ LocalLibProvider,
945
+ ]
946
+
947
+ PROVIDER_MAP: dict[str, type[BaseProvider]] = {
948
+ cls.name: cls for cls in PROVIDERS}
949
+
950
+
951
+ def create_provider(name: str) -> BaseProvider | None:
952
+ """Instancia e retorna o provider de IA correspondente ao ``kind`` solicitado."""
953
+ cls = PROVIDER_MAP.get(name)
954
+ return cls() if cls else None