local-triage 0.0.0-stage → 0.10.0-dev.32
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.
- package/LICENSE +21 -0
- package/README.md +90 -2
- package/THIRD-PARTY-NOTICES.md +48 -0
- package/app/__init__.py +3 -0
- package/app/affiliation.py +137 -0
- package/app/ask.py +300 -0
- package/app/build_info.py +98 -0
- package/app/capec.py +168 -0
- package/app/capec_view.py +27 -0
- package/app/codecmp.py +59 -0
- package/app/config.py +411 -0
- package/app/context.py +1451 -0
- package/app/cvss.py +357 -0
- package/app/db.py +6234 -0
- package/app/defect.py +670 -0
- package/app/defect_check.py +323 -0
- package/app/defect_drafts.py +612 -0
- package/app/defect_dto.py +149 -0
- package/app/defect_fields.py +248 -0
- package/app/defect_form.py +124 -0
- package/app/defect_links.py +107 -0
- package/app/defect_local_text.py +103 -0
- package/app/defect_references.py +164 -0
- package/app/defect_where.py +147 -0
- package/app/ecosystem.py +51 -0
- package/app/executors.py +660 -0
- package/app/feeds.py +1231 -0
- package/app/guard.py +164 -0
- package/app/hub_block_builder.py +200 -0
- package/app/hub_block_version.py +220 -0
- package/app/hub_defects.py +4469 -0
- package/app/hub_effects.py +421 -0
- package/app/hub_entity_versions.py +108 -0
- package/app/hub_import.py +2054 -0
- package/app/hub_onboarding.py +114 -0
- package/app/hub_ops.py +330 -0
- package/app/hub_pull.py +1195 -0
- package/app/hub_state.py +255 -0
- package/app/hub_status.py +237 -0
- package/app/hub_sync.py +619 -0
- package/app/hub_sync_api.py +241 -0
- package/app/hub_sync_compare.py +1054 -0
- package/app/hub_sync_contract.py +75 -0
- package/app/hub_template_model.py +74 -0
- package/app/hub_text_scale.py +159 -0
- package/app/journal.py +250 -0
- package/app/llm.py +850 -0
- package/app/llm_chat.py +596 -0
- package/app/llm_http.py +319 -0
- package/app/llm_messages.py +401 -0
- package/app/llm_net.py +764 -0
- package/app/llm_ollama.py +571 -0
- package/app/lockfile.py +505 -0
- package/app/logsafe.py +54 -0
- package/app/main.py +367 -0
- package/app/mask_display.py +132 -0
- package/app/masking.py +814 -0
- package/app/metrics.py +194 -0
- package/app/model_traffic.py +519 -0
- package/app/models.py +483 -0
- package/app/navigation.py +121 -0
- package/app/osv.py +279 -0
- package/app/package_identity.py +189 -0
- package/app/package_transition.py +824 -0
- package/app/profile_gate.py +71 -0
- package/app/prompts.py +1108 -0
- package/app/provider_keys.py +189 -0
- package/app/providers.py +511 -0
- package/app/routes/__init__.py +10 -0
- package/app/routes/api.py +153 -0
- package/app/routes/capec.py +186 -0
- package/app/routes/common.py +407 -0
- package/app/routes/components.py +1499 -0
- package/app/routes/cwe.py +168 -0
- package/app/routes/decision_selected.py +153 -0
- package/app/routes/defect_add.py +223 -0
- package/app/routes/defect_card_routes.py +363 -0
- package/app/routes/defect_selected.py +342 -0
- package/app/routes/feeds.py +155 -0
- package/app/routes/findings.py +2736 -0
- package/app/routes/hub.py +402 -0
- package/app/routes/hub_bulk.py +288 -0
- package/app/routes/hub_defect_routes.py +1945 -0
- package/app/routes/hub_status_routes.py +1132 -0
- package/app/routes/hub_sync_routes.py +463 -0
- package/app/routes/journal.py +132 -0
- package/app/routes/projects.py +1601 -0
- package/app/routes/providers.py +336 -0
- package/app/routes/references.py +26 -0
- package/app/routes/runs.py +219 -0
- package/app/routes/sca.py +2722 -0
- package/app/routes/settings.py +163 -0
- package/app/run_errors.py +151 -0
- package/app/sca.py +1662 -0
- package/app/sca_contract.py +1289 -0
- package/app/sca_research.py +1089 -0
- package/app/sca_research_net.py +1007 -0
- package/app/sca_text.py +965 -0
- package/app/serve.py +70 -0
- package/app/settings_store.py +262 -0
- package/app/static/app.css +2802 -0
- package/app/static/app.js +3772 -0
- package/app/static/capec-license.txt +9 -0
- package/app/static/favicon.svg +1 -0
- package/app/static/fonts/Golos-Text_DemiBold.woff2 +0 -0
- package/app/static/fonts/Golos-Text_Regular.woff2 +0 -0
- package/app/static/fonts/OFL.txt +90 -0
- package/app/static/navigation.js +234 -0
- package/app/static/observability.js +121 -0
- package/app/static/theme.js +49 -0
- package/app/storage/__init__.py +16 -0
- package/app/storage/local_state.py +246 -0
- package/app/storage/migrate.py +110 -0
- package/app/storage/migrations/postgresql/0001_baseline.sql +896 -0
- package/app/storage/migrations/postgresql/0002_feeds_and_secrets.sql +55 -0
- package/app/storage/migrations/postgresql/0003_project_mask_display.sql +5 -0
- package/app/storage/migrations/postgresql/0004_package_identity.sql +36 -0
- package/app/storage/postgresql.py +573 -0
- package/app/storage/schema.py +619 -0
- package/app/storage/sql.py +57 -0
- package/app/storage/tools.py +254 -0
- package/app/telemetry.py +307 -0
- package/app/templates/base.html +91 -0
- package/app/templates/capec/context.html +3 -0
- package/app/templates/capec/detail.html +27 -0
- package/app/templates/capec/index.html +128 -0
- package/app/templates/components/_archive.html +11 -0
- package/app/templates/components/archived.html +19 -0
- package/app/templates/components/batch.html +35 -0
- package/app/templates/components/detail.html +332 -0
- package/app/templates/components/index.html +338 -0
- package/app/templates/components/research_preview.html +80 -0
- package/app/templates/components/research_run.html +54 -0
- package/app/templates/cwe/bdu.html +56 -0
- package/app/templates/cwe/detail.html +233 -0
- package/app/templates/cwe/index.html +97 -0
- package/app/templates/error.html +8 -0
- package/app/templates/feeds/index.html +65 -0
- package/app/templates/findings/card.html +639 -0
- package/app/templates/findings/decision_selected.html +41 -0
- package/app/templates/findings/defect_add.html +46 -0
- package/app/templates/findings/defect_selected.html +47 -0
- package/app/templates/findings/list.html +153 -0
- package/app/templates/findings/send_selected.html +53 -0
- package/app/templates/findings/trace.html +72 -0
- package/app/templates/journal/detail.html +19 -0
- package/app/templates/journal/index.html +19 -0
- package/app/templates/macros.html +440 -0
- package/app/templates/navigation-fields.html +1 -0
- package/app/templates/navigation.html +11 -0
- package/app/templates/projects/_identity_summary.html +42 -0
- package/app/templates/projects/defect_card.html +153 -0
- package/app/templates/projects/defect_create_preview.html +17 -0
- package/app/templates/projects/defect_fields_diff.html +6 -0
- package/app/templates/projects/defect_fields_form.html +40 -0
- package/app/templates/projects/defect_references.html +17 -0
- package/app/templates/projects/defect_sync_preview.html +28 -0
- package/app/templates/projects/defect_update_actions.html +6 -0
- package/app/templates/projects/defect_update_preview.html +24 -0
- package/app/templates/projects/defects.html +126 -0
- package/app/templates/projects/delete.html +31 -0
- package/app/templates/projects/external.html +61 -0
- package/app/templates/projects/folders.html +64 -0
- package/app/templates/projects/hub_accepted.html +10 -0
- package/app/templates/projects/hub_assignment.html +50 -0
- package/app/templates/projects/hub_pending.html +20 -0
- package/app/templates/projects/hub_pending_list.html +17 -0
- package/app/templates/projects/hub_state_note.html +23 -0
- package/app/templates/projects/hub_step_note.html +5 -0
- package/app/templates/projects/hub_sync.html +105 -0
- package/app/templates/projects/hub_sync_confirm.html +32 -0
- package/app/templates/projects/hub_sync_worker.html +5 -0
- package/app/templates/projects/hub_text_rules.html +64 -0
- package/app/templates/projects/identity_report.html +74 -0
- package/app/templates/projects/list.html +90 -0
- package/app/templates/projects/project.html +433 -0
- package/app/templates/reference-missing.html +14 -0
- package/app/templates/runs/run.html +166 -0
- package/app/templates/sca/card.html +476 -0
- package/app/templates/sca/index.html +321 -0
- package/app/templates/settings/hub_url.html +31 -0
- package/app/templates/settings/index.html +216 -0
- package/app/templates/settings/provider.html +229 -0
- package/app/templates/settings/providers.html +37 -0
- package/app/templates/worklists.html +52 -0
- package/app/textsafe.py +117 -0
- package/app/timing.py +245 -0
- package/app/triage.py +1743 -0
- package/app/view.py +430 -0
- package/app/worklists.py +204 -0
- package/examples/demo/demo-hub-report-v2.xlsx +0 -0
- package/examples/demo/demo-hub-report.xlsx +0 -0
- package/examples/demo/repos/billing-core/pom.xml +30 -0
- package/examples/demo/repos/billing-core/src/main/java/org/example/billing/Invoice.java +9 -0
- package/examples/demo/repos/billing-core/src/main/java/org/example/billing/InvoiceRepository.java +51 -0
- package/examples/demo/repos/billing-core/src/main/java/org/example/billing/InvoiceStatus.java +11 -0
- package/examples/demo/repos/billing-core/src/main/java/org/example/billing/config/DatabaseSettings.java +18 -0
- package/examples/demo/repos/billing-core/src/main/java/org/example/billing/payment/PaymentTokenService.java +35 -0
- package/examples/demo/repos/billing-core/src/main/java/org/example/billing/web/InvoiceExportController.java +57 -0
- package/examples/demo/repos/catalog-api/catalog_api/__init__.py +1 -0
- package/examples/demo/repos/catalog-api/catalog_api/products.py +24 -0
- package/examples/demo/repos/catalog-api/catalog_api/tasks.py +24 -0
- package/examples/demo/repos/catalog-api/catalog_api/views.py +17 -0
- package/examples/demo/repos/catalog-api/requirements.txt +3 -0
- package/npm/build.json +5 -0
- package/npm/cli.js +346 -0
- package/npm/files.manifest +224 -0
- package/npm/lib/binding.js +64 -0
- package/npm/lib/cluster.js +330 -0
- package/npm/lib/env.js +88 -0
- package/npm/lib/fsx.js +125 -0
- package/npm/lib/http.js +53 -0
- package/npm/lib/metrics.js +73 -0
- package/npm/lib/paths.js +150 -0
- package/npm/lib/pg.js +351 -0
- package/npm/lib/proc.js +101 -0
- package/npm/lib/python.js +133 -0
- package/npm/lib/stand.js +46 -0
- package/npm/lib/supervisor.js +1141 -0
- package/npm/lib/version.js +21 -0
- package/npm/requirements.txt +476 -0
- package/npm-shrinkwrap.json +111 -0
- package/package.json +37 -4
|
@@ -0,0 +1,571 @@
|
|
|
1
|
+
"""Клиент локального сервера Ollama: версия, список моделей, загруженные модели и вызов модели с ответом JSON
|
|
2
|
+
(вынесен из app/llm.py в 0.9.12, ADR-0102). Соединение – app/llm_net.py; разбор и проверка ответа – app/llm.py.
|
|
3
|
+
|
|
4
|
+
Облачные модели Ollama отвергаются: по слову cloud в имени и по признакам remote_host, remote_model в /api/tags;
|
|
5
|
+
проверка – перед каждой попыткой вызова модели.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import http.client
|
|
11
|
+
import json
|
|
12
|
+
import re
|
|
13
|
+
import time
|
|
14
|
+
import urllib.parse
|
|
15
|
+
from collections.abc import Callable, Iterable, Mapping
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
from app import model_traffic
|
|
19
|
+
from app.config import model_json_schema_mode
|
|
20
|
+
from app.llm import (DEFAULT_OPTIONS, RAW_KEEP, LlmError, PromptOverflowError, _check_prompt_size, _count,
|
|
21
|
+
_one_line, _retry_messages, _seconds, _token_budget, answer_schema, check_answer, extract_answer,
|
|
22
|
+
is_cloud_model, norm_model_name, retry_message)
|
|
23
|
+
from app.llm_http import ServerClient, _scrub_error, _scrub_value, track_sent, tracked
|
|
24
|
+
from app.llm_net import (ALLOWED_HOSTS, CONNECT_TIMEOUT_S, MAX_RESPONSE_BYTES, _ip, _os_error_text,
|
|
25
|
+
_PinnedHTTPSConnection, _Target, _TooLarge, lan_address_ok)
|
|
26
|
+
from app.models import LlmStats
|
|
27
|
+
|
|
28
|
+
PS_TIMEOUT_S = 5.0 # /api/ps опрашивается часто (метрики), долго ждать нельзя
|
|
29
|
+
UNLOAD_TIMEOUT_S = 30.0 # /api/generate с keep_alive 0 отвечает сразу, но выгрузка большой модели не мгновенна
|
|
30
|
+
THINK_LEVELS = ("low", "medium", "high")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _emit_progress(callback, event):
|
|
34
|
+
if callback is not None:
|
|
35
|
+
try:
|
|
36
|
+
callback(event)
|
|
37
|
+
except Exception:
|
|
38
|
+
pass # Отказ необязательного наблюдателя не меняет ответ и проверку модели.
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def read_chat_stream(chunks, progress):
|
|
42
|
+
"""NDJSON собирается до done; частичный текст не становится ответом или вердиктом."""
|
|
43
|
+
pending=b''
|
|
44
|
+
size=0
|
|
45
|
+
content=[]
|
|
46
|
+
thinking=[]
|
|
47
|
+
final=None
|
|
48
|
+
|
|
49
|
+
def line(raw):
|
|
50
|
+
nonlocal final
|
|
51
|
+
if not raw.strip():return
|
|
52
|
+
if final is not None:raise LlmError('После завершения потока модели получены лишние данные.')
|
|
53
|
+
try:item=json.loads(raw.decode('utf-8'))
|
|
54
|
+
except (ValueError,UnicodeError,RecursionError):raise LlmError('Некорректная строка JSON в потоке модели.') from None
|
|
55
|
+
if not isinstance(item,dict):raise LlmError('Строка потока модели не является объектом JSON.')
|
|
56
|
+
if item.get('error'):raise LlmError(_one_line(item['error']))
|
|
57
|
+
message=item.get('message') or {}
|
|
58
|
+
if not isinstance(message,dict):raise LlmError('Некорректное сообщение потока модели.')
|
|
59
|
+
part=message.get('content') or ''
|
|
60
|
+
thought=message.get('thinking') or ''
|
|
61
|
+
if not isinstance(part,str) or not isinstance(thought,str):raise LlmError('Некорректный текст в потоке модели.')
|
|
62
|
+
if part:content.append(part)
|
|
63
|
+
if thought:thinking.append(thought)
|
|
64
|
+
if part or thought:_emit_progress(progress, {'event':'fragment','received_chars':len(part)+len(thought)})
|
|
65
|
+
if item.get('done') is True:
|
|
66
|
+
final=item
|
|
67
|
+
_emit_progress(progress, {'event':'response_done'})
|
|
68
|
+
|
|
69
|
+
for chunk in chunks:
|
|
70
|
+
size+=len(chunk)
|
|
71
|
+
if size>MAX_RESPONSE_BYTES:raise LlmError('Поток модели превысил предел размера ответа.')
|
|
72
|
+
pending+=chunk
|
|
73
|
+
while b'\n' in pending:
|
|
74
|
+
raw,pending=pending.split(b'\n',1)
|
|
75
|
+
line(raw)
|
|
76
|
+
if pending.strip():line(pending)
|
|
77
|
+
if final is None:raise LlmError('Поток модели завершился без подтверждения завершения ответа.')
|
|
78
|
+
final['message']={'role':'assistant','content':''.join(content),'thinking':''.join(thinking)}
|
|
79
|
+
return final
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
# Сообщения Ollama -> понятное описание; исходный текст остаётся в LlmError.detail.
|
|
83
|
+
_SERVER_ERRORS = (
|
|
84
|
+
(re.compile(r"out of memory|cudamalloc|insufficient memory|requires more system memory|unable to allocate", re.I),
|
|
85
|
+
"модели не хватает памяти (видеопамяти или оперативной): выберите модель меньше или уменьшите окно контекста"),
|
|
86
|
+
(re.compile(r"does not support (?:chat|generate|completion)", re.I),
|
|
87
|
+
"модель не умеет отвечать на сообщения (например, это модель для эмбеддингов)"),
|
|
88
|
+
(re.compile(r"not found", re.I), "модель или путь не найдены на сервере"),
|
|
89
|
+
(re.compile(r"context (?:length|window|size)|prompt is too long|input (?:is )?too long|"
|
|
90
|
+
r"exceeds? (?:the )?(?:maximum )?context", re.I), "промпт не помещается в окно контекста модели"),
|
|
91
|
+
(re.compile(r"runner|terminated|exit status", re.I), "процесс модели на сервере Ollama остановился"),
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def capability_list(value: Any) -> list[str] | None:
|
|
96
|
+
"""Возможности модели (capabilities Ollama) в едином виде: непустой список – списком строк; пусто или иной вид
|
|
97
|
+
(строка, число) – None, «неизвестно»."""
|
|
98
|
+
return [str(c) for c in value] if isinstance(value, list) and value else None
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _describe_server_error(detail: str) -> str:
|
|
102
|
+
return next((text for pattern, text in _SERVER_ERRORS if pattern.search(detail)), "")
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _server_error_text(body: bytes) -> str:
|
|
106
|
+
"""Текст ошибки из тела ответа (Ollama присылает {"error": "..."}), одной строкой."""
|
|
107
|
+
text = body[:64 * 1024].decode("utf-8", errors="replace")
|
|
108
|
+
try:
|
|
109
|
+
parsed = json.loads(text)
|
|
110
|
+
if isinstance(parsed, dict) and parsed.get("error"):
|
|
111
|
+
text = str(parsed["error"])
|
|
112
|
+
except (ValueError, RecursionError):
|
|
113
|
+
pass
|
|
114
|
+
return _one_line(text)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _server_error_message(prefix: str, detail: str) -> str:
|
|
118
|
+
"""Сообщение об ошибке сервера для интерфейса: своё описание, а исходный текст сервера (до 200 знаков) – только
|
|
119
|
+
если своего описания нет. Исходный текст целиком (до DETAIL_MAX знаков) остаётся в LlmError.detail."""
|
|
120
|
+
meaning = _describe_server_error(detail)
|
|
121
|
+
if meaning:
|
|
122
|
+
return f"{prefix}: {meaning}."
|
|
123
|
+
return f"{prefix} (ответ сервера: {detail[:200]})." if detail else f"{prefix}."
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
# ============================================================================ клиент
|
|
127
|
+
|
|
128
|
+
class OllamaClient(ServerClient):
|
|
129
|
+
"""Клиент Ollama. Каждый запрос – отдельное соединение; отказ схемы запоминается потокобезопасной меткой.
|
|
130
|
+
|
|
131
|
+
url – адрес сервера (настройка «Адрес Ollama»); timeout – общий срок ответа модели в chat_json, секунды
|
|
132
|
+
(без потоковой выдачи сервер молчит до конца генерации). Адрес проверяется при каждом запросе (check_url),
|
|
133
|
+
поэтому неверный адрес не мешает создать клиент: ошибка придёт понятным LlmError при первом обращении.
|
|
134
|
+
"""
|
|
135
|
+
|
|
136
|
+
# ---------------------------------------------------------------- адрес и запросы
|
|
137
|
+
|
|
138
|
+
def _target(self) -> _Target:
|
|
139
|
+
if self.trust not in ("local", "lan"):
|
|
140
|
+
raise LlmError(f"Класс доверия «{self.trust}» не поддерживается: запрос к модели не отправлен.")
|
|
141
|
+
hint = (f"нужен адрес вида http://127.0.0.1:11434; разрешённые хосты: {', '.join(ALLOWED_HOSTS)}"
|
|
142
|
+
if self.trust == "local" else "нужен адрес сервера в сети организации, например http://10.0.0.5:11434")
|
|
143
|
+
if not self.url:
|
|
144
|
+
raise LlmError(f"Адрес сервера Ollama не задан (страница «Настройки»): {hint}.")
|
|
145
|
+
try:
|
|
146
|
+
parts = urllib.parse.urlsplit(self.url)
|
|
147
|
+
except ValueError: # например, незакрытая «[» в адресе IPv6
|
|
148
|
+
raise LlmError(f"Адрес сервера Ollama не распознан: {hint}.") from None
|
|
149
|
+
scheme = parts.scheme.lower()
|
|
150
|
+
if scheme not in ("http", "https") or not parts.netloc:
|
|
151
|
+
raise LlmError(f"Адрес сервера Ollama не распознан: {hint}.")
|
|
152
|
+
if scheme == "https" and _PinnedHTTPSConnection is None:
|
|
153
|
+
raise LlmError("В этой сборке Python нет поддержки https: укажите адрес Ollama с http://.")
|
|
154
|
+
if "@" in parts.netloc:
|
|
155
|
+
raise LlmError(f"В адресе сервера Ollama не должно быть имени пользователя и пароля: {hint}.")
|
|
156
|
+
host = (parts.hostname or "").lower()
|
|
157
|
+
if self.trust == "local" and host not in ALLOWED_HOSTS:
|
|
158
|
+
raise LlmError(f"Сервер Ollama «{host}» не входит в разрешённые – запрос не отправлен, код находок "
|
|
159
|
+
f"не должен покидать компьютер: {hint}.")
|
|
160
|
+
if self.trust == "lan":
|
|
161
|
+
ip = _ip(host)
|
|
162
|
+
if not host or ip is not None and not lan_address_ok(ip):
|
|
163
|
+
raise LlmError(f"Адрес сервера «{host}» – не частная сеть: запрос не отправлен, {hint}.")
|
|
164
|
+
try:
|
|
165
|
+
port = parts.port
|
|
166
|
+
except ValueError:
|
|
167
|
+
raise LlmError(f"В адресе сервера Ollama неверный порт: {hint}.") from None
|
|
168
|
+
if parts.query or parts.fragment:
|
|
169
|
+
raise LlmError(f"В адресе сервера Ollama не должно быть «?» и «#»: {hint}.")
|
|
170
|
+
prefix = parts.path.rstrip("/")
|
|
171
|
+
base = urllib.parse.urlunsplit((scheme, parts.netloc, prefix, "", ""))
|
|
172
|
+
return _Target(scheme, host, port or (443 if scheme == "https" else 80), prefix, base)
|
|
173
|
+
|
|
174
|
+
def _read_stream(self, pieces, progress) -> Any:
|
|
175
|
+
return read_chat_stream(pieces, progress)
|
|
176
|
+
|
|
177
|
+
@staticmethod
|
|
178
|
+
def _connect_timeout_error(t: _Target, timeout: float) -> LlmError:
|
|
179
|
+
return LlmError(f"Ollama не отвечает по адресу {t.base}: соединение не установлено за "
|
|
180
|
+
f"{_seconds(min(timeout, CONNECT_TIMEOUT_S))}. Проверьте адрес Ollama на странице "
|
|
181
|
+
"«Настройки» и что Ollama запущена.")
|
|
182
|
+
|
|
183
|
+
@staticmethod
|
|
184
|
+
def _finish(t: _Target, path: str, status: int, body: bytes, secrets: tuple[str, ...],
|
|
185
|
+
headers: dict[str, str]) -> Any:
|
|
186
|
+
"""Ответ Ollama после обмена: перенаправление и ошибка HTTP – LlmError, иначе разобранный JSON без ключа."""
|
|
187
|
+
if 300 <= status < 400:
|
|
188
|
+
raise LlmError(f"Сервер {t.base} ответил перенаправлением (HTTP {status}) на {path}. Перенаправления "
|
|
189
|
+
"не выполняются: укажите адрес Ollama напрямую.", status=status)
|
|
190
|
+
if status >= 400:
|
|
191
|
+
detail = model_traffic.scrub(_server_error_text(body), secrets)
|
|
192
|
+
message = _server_error_message(f"Ollama ({t.base}) ответила ошибкой HTTP {status} на {path}", detail)
|
|
193
|
+
raise _scrub_error(LlmError(message, status=status, detail=detail), secrets)
|
|
194
|
+
try:
|
|
195
|
+
return _scrub_value(json.loads(body.decode("utf-8")), secrets) if body.strip() else {}
|
|
196
|
+
except (ValueError, RecursionError):
|
|
197
|
+
raise LlmError(f"Ответ сервера {t.base} на {path} – не JSON: по этому адресу, похоже, не Ollama.") from None
|
|
198
|
+
|
|
199
|
+
@staticmethod
|
|
200
|
+
def _transport_error(error: BaseException, t: _Target, path: str, timeout: float, expired: bool) -> LlmError:
|
|
201
|
+
"""Сбой на уровне соединения -> LlmError по-русски."""
|
|
202
|
+
if expired or isinstance(error, TimeoutError):
|
|
203
|
+
return LlmError(f"Нет ответа от Ollama ({t.base}) за {_seconds(timeout)} на {path}.")
|
|
204
|
+
if isinstance(error, _TooLarge):
|
|
205
|
+
return LlmError(f"Ответ Ollama ({t.base}) на {path} слишком большой.")
|
|
206
|
+
if isinstance(error, ConnectionRefusedError):
|
|
207
|
+
return LlmError(f"Ollama не отвечает по адресу {t.base}: соединение отклонено. Запустите Ollama и "
|
|
208
|
+
"проверьте адрес Ollama на странице «Настройки».")
|
|
209
|
+
if isinstance(error, (ConnectionResetError, ConnectionAbortedError, BrokenPipeError,
|
|
210
|
+
http.client.HTTPException)):
|
|
211
|
+
return LlmError(f"Связь с Ollama ({t.base}) прервана на {path}: сервер закрыл соединение, не дослав "
|
|
212
|
+
"ответ.")
|
|
213
|
+
return LlmError(f"Ollama не отвечает по адресу {t.base} ({path}): {_os_error_text(error)}.")
|
|
214
|
+
|
|
215
|
+
# ---------------------------------------------------------------- сведения о сервере
|
|
216
|
+
|
|
217
|
+
@tracked
|
|
218
|
+
def version(self) -> str:
|
|
219
|
+
data = self._request("/api/version")
|
|
220
|
+
value = data.get("version") if isinstance(data, dict) else None
|
|
221
|
+
if not isinstance(value, str) or not value.strip():
|
|
222
|
+
raise LlmError(f"В ответе /api/version нет версии: по адресу {self.check_url()}, похоже, не Ollama.")
|
|
223
|
+
return value.strip()
|
|
224
|
+
|
|
225
|
+
def _tags(self) -> list[dict[str, Any]]:
|
|
226
|
+
data = self._request("/api/tags")
|
|
227
|
+
models = data.get("models") if isinstance(data, dict) else None
|
|
228
|
+
if not isinstance(models, list):
|
|
229
|
+
raise LlmError(f"В ответе /api/tags нет списка моделей: по адресу {self.check_url()}, похоже, не Ollama.")
|
|
230
|
+
# имя модели – только строка: иное значение (объект, число) сервером подставлено и в запросы не уходит
|
|
231
|
+
return [m for m in models if isinstance(m, dict) and isinstance(m.get("name") or m.get("model"), str)
|
|
232
|
+
and str(m.get("name") or m.get("model")).strip()]
|
|
233
|
+
|
|
234
|
+
def _capabilities(self, entry: Mapping[str, Any]) -> list[str] | None:
|
|
235
|
+
"""Возможности модели: из /api/tags, а если их там нет или они не списком (старая Ollama, пустой список) – из
|
|
236
|
+
/api/show; неизвестно – None. Одно правило для списка моделей и для сведений о модели (model_info)."""
|
|
237
|
+
capabilities = capability_list(entry.get("capabilities"))
|
|
238
|
+
if capabilities is not None:
|
|
239
|
+
return capabilities
|
|
240
|
+
try:
|
|
241
|
+
info = self._request("/api/show", {"model": str(entry.get("name") or entry.get("model"))})
|
|
242
|
+
except LlmError:
|
|
243
|
+
return None
|
|
244
|
+
return capability_list(info.get("capabilities") if isinstance(info, dict) else None)
|
|
245
|
+
|
|
246
|
+
@tracked
|
|
247
|
+
def list_models(self) -> list[dict[str, Any]]:
|
|
248
|
+
"""Локальные модели, пригодные для разбора, по имени: name, size (байты), params, quant, family,
|
|
249
|
+
context_length, capabilities. Облачные модели и модели без генерации текста (эмбеддинги) не входят;
|
|
250
|
+
если возможности модели неизвестны, модель с «embed» в имени или семейства bert считается эмбеддингом."""
|
|
251
|
+
result = []
|
|
252
|
+
for m in self._tags():
|
|
253
|
+
if is_cloud_model(m):
|
|
254
|
+
continue
|
|
255
|
+
name = str(m.get("name") or m.get("model")).strip()
|
|
256
|
+
details = m.get("details") if isinstance(m.get("details"), dict) else {}
|
|
257
|
+
capabilities = self._capabilities(m)
|
|
258
|
+
if capabilities is not None:
|
|
259
|
+
if "completion" not in capabilities:
|
|
260
|
+
continue
|
|
261
|
+
elif "embed" in name.casefold() or "bert" in str(details.get("family") or "").casefold():
|
|
262
|
+
continue
|
|
263
|
+
context = details.get("context_length")
|
|
264
|
+
result.append({
|
|
265
|
+
"name": name,
|
|
266
|
+
"size": _count(m.get("size")),
|
|
267
|
+
"digest": str(m.get("digest") or "")[:128],
|
|
268
|
+
"params": str(details.get("parameter_size") or ""),
|
|
269
|
+
"quant": str(details.get("quantization_level") or ""),
|
|
270
|
+
"family": str(details.get("family") or ""),
|
|
271
|
+
"context_length": context if _count(context) else None,
|
|
272
|
+
"capabilities": capabilities,
|
|
273
|
+
})
|
|
274
|
+
return sorted(result, key=lambda x: x["name"].casefold())
|
|
275
|
+
|
|
276
|
+
@tracked
|
|
277
|
+
def ps(self) -> list[dict[str, Any]]:
|
|
278
|
+
"""Загруженные в память модели: name, size и size_vram (байты), context (окно контекста или None)."""
|
|
279
|
+
data = self._request("/api/ps", timeout=PS_TIMEOUT_S)
|
|
280
|
+
models = data.get("models") if isinstance(data, dict) else None
|
|
281
|
+
if not isinstance(models, list):
|
|
282
|
+
raise LlmError("В ответе /api/ps нет списка моделей: по этому адресу, похоже, не Ollama.")
|
|
283
|
+
result = []
|
|
284
|
+
for m in models:
|
|
285
|
+
if not isinstance(m, dict):
|
|
286
|
+
continue
|
|
287
|
+
context = m.get("context_length")
|
|
288
|
+
result.append({
|
|
289
|
+
"name": str(m.get("name") or m.get("model") or ""),
|
|
290
|
+
"size": _count(m.get("size")),
|
|
291
|
+
"size_vram": _count(m.get("size_vram")),
|
|
292
|
+
"context": context if _count(context) else None,
|
|
293
|
+
})
|
|
294
|
+
return result
|
|
295
|
+
|
|
296
|
+
@tracked
|
|
297
|
+
def unload_model(self, model: str) -> dict[str, Any]:
|
|
298
|
+
"""Выгрузить модель из памяти Ollama: POST /api/generate с keep_alive 0. Это не запрос к модели: текст
|
|
299
|
+
находки не отправляется, ответ сервера – только подтверждение выгрузки. Нужна перезагрузка модели заново,
|
|
300
|
+
когда она работает заметно медленнее обычного (app/triage.py). Любой сбой – LlmError."""
|
|
301
|
+
name = str(model or "").strip()
|
|
302
|
+
if not name:
|
|
303
|
+
raise LlmError("Не выбрана модель.")
|
|
304
|
+
data = self._request("/api/generate", {"model": name, "keep_alive": 0}, timeout=UNLOAD_TIMEOUT_S)
|
|
305
|
+
return data if isinstance(data, dict) else {}
|
|
306
|
+
|
|
307
|
+
@tracked
|
|
308
|
+
def warm_model(self, model: str, num_ctx: int, timeout: float = 600.0) -> None:
|
|
309
|
+
"""Загрузить модель в память заранее (прогрев ВМ при загрузке): POST /api/generate без текста, с окном
|
|
310
|
+
контекста профиля и keep_alive 24h. Модель – та, что на сервере под этим именем, и не облачная. Право на
|
|
311
|
+
генерацию берёт вызывающий. Загрузка подтверждается ответом с done = true без ошибки; иначе (и при сбое) –
|
|
312
|
+
LlmError."""
|
|
313
|
+
name = str(model or "").strip()
|
|
314
|
+
self.model_info(name)
|
|
315
|
+
data = self._request("/api/generate", {"model": name, "keep_alive": "24h",
|
|
316
|
+
"options": {"num_ctx": int(num_ctx)}}, timeout=timeout)
|
|
317
|
+
if not isinstance(data, dict) or data.get("error") or data.get("done") is not True:
|
|
318
|
+
reason = _one_line(data.get("error")) if isinstance(data, dict) and data.get("error") else \
|
|
319
|
+
"в ответе нет подтверждения загрузки (done)"
|
|
320
|
+
raise LlmError(f"Модель «{name}» не прогрета: {reason}.")
|
|
321
|
+
|
|
322
|
+
@tracked
|
|
323
|
+
def probe(self, model: str, timeout: float = 120.0) -> float:
|
|
324
|
+
"""Пробная генерация («Проверить» в профиле, ADR-0102): один короткий ответ модели -> секунды. Модель – та,
|
|
325
|
+
что лежит на сервере под этим именем, и не облачная. Право на генерацию берёт вызывающий
|
|
326
|
+
(executors.probe_generation)."""
|
|
327
|
+
name = str(model or "").strip()
|
|
328
|
+
if self.before_send is not None:
|
|
329
|
+
self.before_send()
|
|
330
|
+
self.model_info(name)
|
|
331
|
+
started = time.monotonic()
|
|
332
|
+
data = self._request("/api/chat", {"model": name, "stream": False,
|
|
333
|
+
"messages": [{"role": "user", "content": "Ответь одним словом: готов."}],
|
|
334
|
+
"options": {"num_predict": 8, "temperature": 0}}, timeout=timeout)
|
|
335
|
+
message = data.get("message") if isinstance(data, dict) else None
|
|
336
|
+
text = [message.get(k) for k in ("content", "thinking")] if isinstance(message, dict) else []
|
|
337
|
+
if (not isinstance(data, dict) or data.get("error") or data.get("done") is not True
|
|
338
|
+
or not any(isinstance(v, str) and v.strip() for v in text)
|
|
339
|
+
or any(v is not None and not isinstance(v, str) for v in text)):
|
|
340
|
+
raise LlmError(f"Пробная генерация не удалась: сервер {self.check_url()} не вернул ответ модели.")
|
|
341
|
+
return time.monotonic() - started
|
|
342
|
+
|
|
343
|
+
@tracked
|
|
344
|
+
def model_info(self, model: str) -> dict[str, Any]:
|
|
345
|
+
"""Запись /api/tags о модели. Модели нет на сервере или она облачная – LlmError. Без кэша: перед каждой
|
|
346
|
+
отправкой кода проверяется то, что сейчас лежит на сервере под этим именем."""
|
|
347
|
+
name = str(model or "").strip()
|
|
348
|
+
if not name:
|
|
349
|
+
raise LlmError("Не выбрана модель.")
|
|
350
|
+
if "cloud" in name.casefold():
|
|
351
|
+
raise LlmError(_cloud_text(name))
|
|
352
|
+
key = norm_model_name(name)
|
|
353
|
+
entry = next((m for m in self._tags()
|
|
354
|
+
if key in (norm_model_name(m.get("name")), norm_model_name(m.get("model")))), None)
|
|
355
|
+
if entry is None:
|
|
356
|
+
raise LlmError(f"Модели «{name}» нет на сервере Ollama ({self.check_url()}). Загрузите её командой: "
|
|
357
|
+
f"ollama pull {name}")
|
|
358
|
+
if is_cloud_model(entry):
|
|
359
|
+
raise LlmError(_cloud_text(name))
|
|
360
|
+
# возможности – в едином виде (список строк или None, «неизвестно»): старая Ollama, пустой список или иной вид –
|
|
361
|
+
# из /api/show, как в списке моделей
|
|
362
|
+
return {**entry, "capabilities": self._capabilities(entry)}
|
|
363
|
+
|
|
364
|
+
# ---------------------------------------------------------------- вызов модели
|
|
365
|
+
|
|
366
|
+
def chat_json(self, *args: Any, **kwargs: Any) -> tuple[dict[str, Any], LlmStats]:
|
|
367
|
+
"""Ответ модели в виде объекта JSON (см. _chat_json). Разобранный объект и ошибки – без значений ключа
|
|
368
|
+
профиля: модель или сервер могли вернуть ключ внутри JSON ответа, в экранированном виде."""
|
|
369
|
+
try:
|
|
370
|
+
with track_sent(): # ушёл хоть один запрос обращения – у ошибки sent = True (К11 плана 0.9.13)
|
|
371
|
+
obj, stats = self._chat_json(*args, **kwargs)
|
|
372
|
+
except LlmError as e:
|
|
373
|
+
raise _scrub_error(e, self._secrets) from None
|
|
374
|
+
return _scrub_value(obj, self._secrets), stats
|
|
375
|
+
|
|
376
|
+
def _chat_json(self, model: str, messages: list[dict[str, Any]], fields: Mapping[str, str],
|
|
377
|
+
required: Iterable[str], enums: Mapping[str, Iterable[str]], options: Mapping[str, Any] | None = None,
|
|
378
|
+
think: str | bool | None | Callable[[Mapping[str, Any]], str | bool | None] = None,
|
|
379
|
+
types: Mapping[str, str] | None = None,
|
|
380
|
+
validate: Callable[[dict[str, Any]], Iterable[str]] | None = None, progress=None,
|
|
381
|
+
json_schema: str = ""
|
|
382
|
+
) -> tuple[dict[str, Any], LlmStats]:
|
|
383
|
+
"""Один ответ модели в виде объекта JSON -> (объект, замеры).
|
|
384
|
+
|
|
385
|
+
fields – ключ -> описание (ключи называются в сообщении при повторе; сами поля перечисляет промпт);
|
|
386
|
+
required – обязательные ключи; enums – допустимые значения; types – необязательно: ключ -> тип из TYPE_NAMES
|
|
387
|
+
для мягкого приведения и проверки; validate – необязательно: проверка ответа по существу после приведения
|
|
388
|
+
типов (объект -> список замечаний по-русски; например, поле, которое может быть пустым только при одном
|
|
389
|
+
вердикте). Замечания validate, как и ошибки формата, ведут к повтору. options – параметры генерации поверх
|
|
390
|
+
DEFAULT_OPTIONS. think – уровень рассуждения, разрешённый вызывающим (executors.applied_think): значение (low,
|
|
391
|
+
medium, high или None – поле не передаётся) или функция от записи /api/tags модели – тогда уровень
|
|
392
|
+
вычисляется на каждую отправку по модели, которая в этот момент лежит на сервере. Клиент сам уровень не
|
|
393
|
+
выбирает; ушедшие уровни – в stats.think. before_send (проверка допуска профиля) вызывается до любых
|
|
394
|
+
обращений попытки и перед самой отправкой; при сбое предварительного обращения допуск проверяется снова.
|
|
395
|
+
|
|
396
|
+
Перед каждой попыткой модель заново проверяется на сервере (есть и не облачная), а промпт – на размер окна
|
|
397
|
+
контекста. Объект JSON, закрытый до обрыва по длине (done_reason = length), принимается: он целый и прошёл
|
|
398
|
+
проверку; оборванный объект – LlmError без повтора. Сбой сервера и два ответа не по формату – LlmError;
|
|
399
|
+
в её stats – замеры сделанных попыток.
|
|
400
|
+
"""
|
|
401
|
+
name = str(model or "").strip()
|
|
402
|
+
opts = dict(DEFAULT_OPTIONS)
|
|
403
|
+
opts.update(options or {})
|
|
404
|
+
_check_prompt_size(messages, opts)
|
|
405
|
+
required = list(required)
|
|
406
|
+
enums = {k: list(v) for k, v in enums.items()}
|
|
407
|
+
mode = model_json_schema_mode(json_schema)
|
|
408
|
+
schema = answer_schema(fields, required, enums, types)
|
|
409
|
+
base_messages = [dict(m) for m in messages]
|
|
410
|
+
body: dict[str, Any] = {"model": name, "messages": base_messages, "stream": progress is not None, "options": opts}
|
|
411
|
+
started = time.monotonic()
|
|
412
|
+
totals = {"prompt_eval_count": 0, "eval_count": 0, "prompt_eval_duration": 0, "eval_duration": 0,
|
|
413
|
+
"load_duration": 0}
|
|
414
|
+
problems: list[str] = []
|
|
415
|
+
content = ""
|
|
416
|
+
window = _token_budget(opts, safety=False)
|
|
417
|
+
sent_think: list[str] = [] # уровень каждой попытки отправки после успешного допуска
|
|
418
|
+
level_now = ["-"]
|
|
419
|
+
|
|
420
|
+
def put_think(info: Mapping[str, Any]) -> None:
|
|
421
|
+
"""Уровень рассуждения этой отправки – решение вызывающего (ADR-0102), клиент не выбирает сам."""
|
|
422
|
+
level = think(info) if callable(think) else think
|
|
423
|
+
body.pop("think", None)
|
|
424
|
+
if level in THINK_LEVELS or isinstance(level, bool): # уровень gpt-oss или true/false другим моделям
|
|
425
|
+
body["think"] = level
|
|
426
|
+
level_now[0] = (level if level in THINK_LEVELS else "on" if level is True else "off" if level is False
|
|
427
|
+
else "-")
|
|
428
|
+
|
|
429
|
+
def admit() -> None:
|
|
430
|
+
if self.before_send is not None:
|
|
431
|
+
self.before_send()
|
|
432
|
+
|
|
433
|
+
def send() -> dict[str, Any]:
|
|
434
|
+
"""Допуск непосредственно перед отправкой и сама отправка; уровень записывается у попытки, прошедшей
|
|
435
|
+
допуск (сбой сети до передачи байтов её не отменяет – это попытка, а не ответ)."""
|
|
436
|
+
admit()
|
|
437
|
+
sent_think.append(level_now[0])
|
|
438
|
+
return self._chat(body, name, progress=progress) if progress is not None else self._chat(body, name)
|
|
439
|
+
|
|
440
|
+
def stats(attempts: int) -> LlmStats:
|
|
441
|
+
result = _stats(name, totals, attempts, started)
|
|
442
|
+
result.think = ",".join(sent_think)
|
|
443
|
+
return result
|
|
444
|
+
|
|
445
|
+
for attempt in (1, 2):
|
|
446
|
+
try:
|
|
447
|
+
admit() # допуск – до любых обращений попытки, даже к списку моделей
|
|
448
|
+
body.pop("format", None)
|
|
449
|
+
if not self._schema_unsupported.is_set() and (mode == "always" or mode == "retry" and attempt == 2):
|
|
450
|
+
body["format"] = schema
|
|
451
|
+
put_think(self.model_info(name)) # перед каждой отправкой кода: модель есть и не облачная
|
|
452
|
+
if progress is not None:
|
|
453
|
+
_emit_progress(progress, {'event':'request_started','attempt':attempt})
|
|
454
|
+
try:
|
|
455
|
+
data = send()
|
|
456
|
+
except LlmError as e:
|
|
457
|
+
if ("format" not in body or e.status != 400
|
|
458
|
+
or not re.search(r"\b(?:format|schema)\b", e.detail, re.IGNORECASE)):
|
|
459
|
+
raise
|
|
460
|
+
self._schema_unsupported.set()
|
|
461
|
+
body.pop("format")
|
|
462
|
+
admit() # повтор без схемы: допуск – снова до проверки модели
|
|
463
|
+
put_think(self.model_info(name))
|
|
464
|
+
data = send()
|
|
465
|
+
except LlmError as e:
|
|
466
|
+
if self.before_send is not None:
|
|
467
|
+
try: # сбой предварительного обращения (модели нет и т. п.): сначала – не выключен ли профиль
|
|
468
|
+
self.before_send()
|
|
469
|
+
except LlmError as refused:
|
|
470
|
+
refused.stats = stats(attempt)
|
|
471
|
+
raise refused from None
|
|
472
|
+
e.stats = stats(attempt)
|
|
473
|
+
raise
|
|
474
|
+
for key in totals:
|
|
475
|
+
totals[key] += _count(data.get(key))
|
|
476
|
+
message = data.get("message") if isinstance(data.get("message"), dict) else {}
|
|
477
|
+
content = str(message.get("content") or "")
|
|
478
|
+
# Оценка длины – эвристика: сверяется счёт самой модели, у каждой попытки отдельно (до сложения
|
|
479
|
+
# замеров). Не поместилось – ответу этой попытки не доверяем, повтор не нужен.
|
|
480
|
+
used = _count(data.get("prompt_eval_count"))
|
|
481
|
+
if window and used > window:
|
|
482
|
+
raise PromptOverflowError(
|
|
483
|
+
f"Промпт, по счёту модели ({used} токенов), не поместился в окно контекста вместе с ответом "
|
|
484
|
+
f"({window} токенов): начало могло быть обрезано, ответ не принят.",
|
|
485
|
+
stats=stats(attempt), raw=content[:RAW_KEEP])
|
|
486
|
+
obj, why = extract_answer(content, [*fields, *required])
|
|
487
|
+
if obj is None:
|
|
488
|
+
problems = [why or _no_json_reason(content, message)]
|
|
489
|
+
else:
|
|
490
|
+
obj, problems = check_answer(obj, required, enums, types)
|
|
491
|
+
if not problems and validate is not None:
|
|
492
|
+
problems = [str(p) for p in validate(obj) if str(p).strip()]
|
|
493
|
+
if not problems:
|
|
494
|
+
return obj, stats(attempt)
|
|
495
|
+
if str(data.get("done_reason") or "") == "length":
|
|
496
|
+
raise LlmError(_length_text(opts.get("num_predict"), content, message, body.get("think")),
|
|
497
|
+
stats=stats(attempt), raw=content[:RAW_KEEP])
|
|
498
|
+
if attempt == 1:
|
|
499
|
+
try:
|
|
500
|
+
body["messages"] = _retry_messages(base_messages, content,
|
|
501
|
+
retry_message(problems, fields, enums), opts, echo=mode == "off")
|
|
502
|
+
if mode != "off" and opts.get("seed") is not None:
|
|
503
|
+
body["options"] = {**opts, "seed": opts["seed"] + 1}
|
|
504
|
+
except LlmError as e:
|
|
505
|
+
e.stats, e.raw = stats(attempt), content[:RAW_KEEP]
|
|
506
|
+
raise
|
|
507
|
+
raise LlmError(f"Модель дважды ответила не по формату: {'; '.join(problems[:5])}.",
|
|
508
|
+
stats=stats(2), raw=content[:RAW_KEEP])
|
|
509
|
+
|
|
510
|
+
def _chat(self, body: dict[str, Any], name: str, progress=None) -> dict[str, Any]:
|
|
511
|
+
try:
|
|
512
|
+
data = self._request("/api/chat", body, timeout=self.timeout, progress=progress) if progress is not None else self._request("/api/chat",body,timeout=self.timeout)
|
|
513
|
+
except LlmError as e:
|
|
514
|
+
if e.status == 404 and "not found" in e.detail.casefold():
|
|
515
|
+
raise LlmError(f"Модели «{name}» нет на сервере Ollama ({self.check_url()}). Загрузите её "
|
|
516
|
+
f"командой: ollama pull {name}", status=404, detail=e.detail) from None
|
|
517
|
+
raise
|
|
518
|
+
if not isinstance(data, dict):
|
|
519
|
+
raise LlmError("Ответ /api/chat – не объект JSON.")
|
|
520
|
+
if data.get("error"):
|
|
521
|
+
detail = _one_line(data["error"])
|
|
522
|
+
raise LlmError(_server_error_message("Ollama вернула ошибку на /api/chat", detail), detail=detail)
|
|
523
|
+
return data
|
|
524
|
+
|
|
525
|
+
|
|
526
|
+
def _cloud_text(name: str) -> str:
|
|
527
|
+
return (f"Модель «{name}» облачная: запросы к ней уходят с компьютера, а код находок должен оставаться "
|
|
528
|
+
"на месте. Выберите локальную модель.")
|
|
529
|
+
|
|
530
|
+
|
|
531
|
+
def _length_text(limit: Any, content: str, message: Mapping[str, Any], think: Any) -> str:
|
|
532
|
+
"""Обрыв по длине (done_reason = length) – что произошло и какое поле профиля менять. Отдельный предел с
|
|
533
|
+
рассуждением действует только при think = true (executors.request_options): тогда поле – «Предел ответа с
|
|
534
|
+
рассуждением» (не больше половины окна контекста) и рассуждение можно выключить. У gpt-oss (уровень low, medium,
|
|
535
|
+
high – выключить нельзя) и без рассуждения действует «Предел ответа разбора» (не больше четверти окна). Совет
|
|
536
|
+
«увеличьте num_predict» без названия поля уводил не туда."""
|
|
537
|
+
if not content.strip() and str(message.get("thinking") or "").strip():
|
|
538
|
+
what = f"модель рассуждала и не дошла до ответа за {limit} токенов (num_predict = {limit})"
|
|
539
|
+
else:
|
|
540
|
+
what = f"исчерпан предел длины ответа (num_predict = {limit})"
|
|
541
|
+
if think is True:
|
|
542
|
+
how = ("Для разбора находок поднимите «Предел ответа с рассуждением» в профиле модели (не больше половины "
|
|
543
|
+
"окна контекста – при нехватке поднимите и окно), выключите рассуждение или выберите другую модель.")
|
|
544
|
+
else:
|
|
545
|
+
how = ("Для разбора находок поднимите «Предел ответа разбора» в профиле модели (не больше четверти окна "
|
|
546
|
+
"контекста) или выберите другую модель.")
|
|
547
|
+
return f"Ответ модели оборван: {what}. {how}"
|
|
548
|
+
|
|
549
|
+
|
|
550
|
+
def _no_json_reason(content: str, message: Mapping[str, Any]) -> str:
|
|
551
|
+
if not content.strip():
|
|
552
|
+
if str(message.get("thinking") or "").strip():
|
|
553
|
+
return "ответ пуст: модель не закончила рассуждение"
|
|
554
|
+
return "пустой ответ"
|
|
555
|
+
return "в ответе нет объекта JSON"
|
|
556
|
+
|
|
557
|
+
|
|
558
|
+
def _stats(model: str, totals: Mapping[str, int], attempts: int, started: float) -> LlmStats:
|
|
559
|
+
"""Замеры по всем попыткам: токены и длительности сервера суммируются; ток/с = токены / время генерации."""
|
|
560
|
+
eval_s = totals["eval_duration"] / 1e9
|
|
561
|
+
prompt_s = totals["prompt_eval_duration"] / 1e9
|
|
562
|
+
return LlmStats(
|
|
563
|
+
model=model,
|
|
564
|
+
prompt_tokens=totals["prompt_eval_count"],
|
|
565
|
+
output_tokens=totals["eval_count"],
|
|
566
|
+
eval_tps=round(totals["eval_count"] / eval_s, 2) if eval_s > 0 else 0.0,
|
|
567
|
+
prompt_tps=round(totals["prompt_eval_count"] / prompt_s, 2) if prompt_s > 0 else 0.0,
|
|
568
|
+
total_s=round(time.monotonic() - started, 3),
|
|
569
|
+
load_s=round(totals["load_duration"] / 1e9, 3),
|
|
570
|
+
attempts=attempts,
|
|
571
|
+
)
|