argos-cli 0.3.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.
- argos/__init__.py +5 -0
- argos/__main__.py +4 -0
- argos/adapters/__init__.py +9 -0
- argos/adapters/_libreoffice_worker.py +111 -0
- argos/adapters/ai.py +1506 -0
- argos/adapters/ai_remote.py +654 -0
- argos/adapters/attachment_conversion.py +132 -0
- argos/adapters/capabilities.py +31 -0
- argos/adapters/chart_render.py +72 -0
- argos/adapters/docx_pdf.py +2953 -0
- argos/adapters/limesurvey.py +1079 -0
- argos/adapters/model_call.py +274 -0
- argos/adapters/report_publication.py +1530 -0
- argos/adapters/url_fetch.py +146 -0
- argos/adapters/xlsx.py +454 -0
- argos/analytics.py +731 -0
- argos/assets.py +257 -0
- argos/audit_result.py +369 -0
- argos/booleans.py +105 -0
- argos/catalog.py +1205 -0
- argos/cli.py +606 -0
- argos/contracts.py +532 -0
- argos/core.py +325 -0
- argos/default_skills/README.md +23 -0
- argos/default_skills/criar-matriz-planejamento/SKILL.md +200 -0
- argos/default_skills/elaborar-survey-limesurvey/SKILL.md +106 -0
- argos/default_skills/operar-argos/SKILL.md +74 -0
- argos/default_skills/verificar-diretrizes-fiscalizacao/SKILL.md +129 -0
- argos/default_skills/verificar-diretrizes-fiscalizacao/assets/relatorio-avaliacao.md +54 -0
- argos/default_skills/verificar-diretrizes-fiscalizacao/references/contrato-saidas.md +36 -0
- argos/default_skills/verificar-diretrizes-fiscalizacao/references/papeis-das-pastas.md +37 -0
- argos/default_skills/verificar-diretrizes-fiscalizacao/references/roteiro-verificacoes.md +27 -0
- argos/default_skills/verificar-diretrizes-fiscalizacao/scripts/avaliacao.py +253 -0
- argos/engines/__init__.py +3 -0
- argos/engines/adjustments.py +571 -0
- argos/engines/analytics.py +195 -0
- argos/engines/audit.py +2730 -0
- argos/engines/evaluation.py +6088 -0
- argos/engines/index.py +1683 -0
- argos/engines/matrix.py +5736 -0
- argos/engines/matrix_html.py +698 -0
- argos/engines/model_request.py +201 -0
- argos/engines/report_document.py +137 -0
- argos/engines/reports.py +1200 -0
- argos/engines/survey.py +4445 -0
- argos/envfile.py +53 -0
- argos/errors.py +29 -0
- argos/evidence_staging.py +293 -0
- argos/executions.py +565 -0
- argos/findings_matrix.py +2549 -0
- argos/fingerprints.py +487 -0
- argos/index_dsl.py +2100 -0
- argos/matrix_markdown.py +475 -0
- argos/matrix_widths.py +280 -0
- argos/pipeline.py +1745 -0
- argos/products.py +220 -0
- argos/progress.py +221 -0
- argos/project.py +608 -0
- argos/report_config.py +158 -0
- argos/resources/ESPECIFICACAO_MARKDOWN_MATRIZ_ACHADOS.md +539 -0
- argos/resources/ESPECIFICACAO_MARKDOWN_MATRIZ_PLANEJAMENTO.md +1000 -0
- argos/resources/ESPECIFICACAO_UNIFICADA_MATRIZES_V1_3.md +1142 -0
- argos/resources/anexo-evidencias-base.docx +0 -0
- argos/resources/argos-index-dsl-v1.schema.json +539 -0
- argos/resources/argos-report-config-v1.schema.json +113 -0
- argos/resources/diretrizes-projeto.md +476 -0
- argos/resources/env.example +37 -0
- argos/resources/exemplos/matriz_achados_boilerplate.md +61 -0
- argos/resources/exemplos/matriz_achados_draft.md +106 -0
- argos/resources/exemplos/matriz_achados_larguras_v1_3.md +114 -0
- argos/resources/exemplos/matriz_achados_v1_3.md +107 -0
- argos/resources/exemplos/matriz_planejamento_boilerplate.md +64 -0
- argos/resources/exemplos/matriz_planejamento_larguras_v1_3.md +115 -0
- argos/resources/exemplos/matriz_planejamento_v1_3.md +108 -0
- argos/resources/template-base-estilos-sigiloso.docx +0 -0
- argos/resources/template-base-estilos.docx +0 -0
- argos/resources/template-matriz-planejamento.docx +0 -0
- argos/resources/template-relatorio-consolidado-comum.docx +0 -0
- argos/resources/template-relatorio-consolidado-institucional.docx +0 -0
- argos/response_profiles.py +856 -0
- argos/scheduler.py +142 -0
- argos/status.py +367 -0
- argos/store.py +1228 -0
- argos/survey_collection.py +832 -0
- argos/telemetry.py +84 -0
- argos/tui.py +1262 -0
- argos/tui.tcss +827 -0
- argos/tui_models.py +466 -0
- argos/tui_path.py +155 -0
- argos/tui_widgets.py +482 -0
- argos/version.py +3 -0
- argos_cli-0.3.1.dist-info/METADATA +570 -0
- argos_cli-0.3.1.dist-info/RECORD +96 -0
- argos_cli-0.3.1.dist-info/WHEEL +5 -0
- argos_cli-0.3.1.dist-info/entry_points.txt +2 -0
- argos_cli-0.3.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
"""Chamada a um modelo com troca de chave, nova tentativa e erro sanitizado.
|
|
2
|
+
|
|
3
|
+
Um único *module* para os quatro providers: cada adapter entrega ``send(chave)``,
|
|
4
|
+
que executa **uma** tentativa completa (HTTP ou SDK), e recebe de volta o valor ou
|
|
5
|
+
um ``AIServiceError`` pronto. A política é:
|
|
6
|
+
|
|
7
|
+
* ``429`` (ou ``RESOURCE_EXHAUSTED``): troca para a próxima chave na hora; sem chave
|
|
8
|
+
sobrando, falha como ``retryable`` sem esperar;
|
|
9
|
+
* ``500/502/503/504``: repete na mesma chave, com esperas configuráveis (ou o
|
|
10
|
+
``Retry-After``, limitado a ``max_wait``);
|
|
11
|
+
* qualquer outra falha (timeout, transporte, resposta inválida): não é repetida e
|
|
12
|
+
fica ``unknown`` quando não há código HTTP, porque a chamada pode ter sido
|
|
13
|
+
cobrada e o reenvio automático duplicaria o custo.
|
|
14
|
+
|
|
15
|
+
Chaves nunca aparecem em mensagens, eventos ou resultados (só ``chave-N``).
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import datetime as dt
|
|
21
|
+
import os
|
|
22
|
+
import threading
|
|
23
|
+
import time
|
|
24
|
+
import urllib.error
|
|
25
|
+
from dataclasses import dataclass
|
|
26
|
+
from email.utils import parsedate_to_datetime
|
|
27
|
+
from typing import Any, Callable, Iterable, Sequence, TypeVar
|
|
28
|
+
|
|
29
|
+
from ..core import ArgosError, InputValidationError
|
|
30
|
+
|
|
31
|
+
T = TypeVar("T")
|
|
32
|
+
|
|
33
|
+
# 529 é o "overloaded" da API da Anthropic.
|
|
34
|
+
TRANSIENT_STATUSES = frozenset({500, 502, 503, 504, 529})
|
|
35
|
+
RATE_LIMIT_STATUS = 429
|
|
36
|
+
DEFAULT_RETRY_DELAYS = (30.0, 60.0, 120.0)
|
|
37
|
+
DEFAULT_MAX_WAIT_SECONDS = 180.0
|
|
38
|
+
DEFAULT_TIMEOUT_SECONDS = 120.0
|
|
39
|
+
DETAIL_LIMIT = 300
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class AIServiceError(ArgosError):
|
|
43
|
+
"""Falha sanitizada de transporte ou resposta de um provider."""
|
|
44
|
+
|
|
45
|
+
def __init__(
|
|
46
|
+
self,
|
|
47
|
+
message: str,
|
|
48
|
+
*,
|
|
49
|
+
http_status: int | None = None,
|
|
50
|
+
retryable: bool = False,
|
|
51
|
+
unknown: bool = False,
|
|
52
|
+
) -> None:
|
|
53
|
+
super().__init__(message)
|
|
54
|
+
self.http_status = http_status
|
|
55
|
+
self.retryable = retryable
|
|
56
|
+
self.unknown = unknown
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@dataclass(frozen=True)
|
|
60
|
+
class ModelCallPolicy:
|
|
61
|
+
"""Esperas entre repetições, teto de espera, timeout e relógio (injetável nos testes)."""
|
|
62
|
+
|
|
63
|
+
delays: tuple[float, ...] = DEFAULT_RETRY_DELAYS
|
|
64
|
+
max_wait: float = DEFAULT_MAX_WAIT_SECONDS
|
|
65
|
+
timeout: float = DEFAULT_TIMEOUT_SECONDS
|
|
66
|
+
sleeper: Callable[[float], None] = time.sleep
|
|
67
|
+
|
|
68
|
+
@classmethod
|
|
69
|
+
def from_env(cls) -> "ModelCallPolicy":
|
|
70
|
+
"""``ARGOS_AI_RETRY_DELAYS`` (lista em segundos; vazio desliga) e ``ARGOS_AI_TIMEOUT_SECONDS``."""
|
|
71
|
+
delays = DEFAULT_RETRY_DELAYS
|
|
72
|
+
raw_delays = os.environ.get("ARGOS_AI_RETRY_DELAYS")
|
|
73
|
+
if raw_delays is not None:
|
|
74
|
+
try:
|
|
75
|
+
delays = tuple(float(part) for part in raw_delays.split(",") if part.strip())
|
|
76
|
+
except ValueError as exc:
|
|
77
|
+
raise InputValidationError(
|
|
78
|
+
"ARGOS_AI_RETRY_DELAYS deve ser uma lista de segundos separada por vírgula"
|
|
79
|
+
) from exc
|
|
80
|
+
if any(value < 0 for value in delays):
|
|
81
|
+
raise InputValidationError("ARGOS_AI_RETRY_DELAYS não aceita valores negativos")
|
|
82
|
+
timeout = DEFAULT_TIMEOUT_SECONDS
|
|
83
|
+
raw_timeout = os.environ.get("ARGOS_AI_TIMEOUT_SECONDS")
|
|
84
|
+
if raw_timeout:
|
|
85
|
+
try:
|
|
86
|
+
timeout = float(raw_timeout)
|
|
87
|
+
except ValueError as exc:
|
|
88
|
+
raise InputValidationError("ARGOS_AI_TIMEOUT_SECONDS deve ser um número de segundos") from exc
|
|
89
|
+
if timeout <= 0:
|
|
90
|
+
raise InputValidationError("ARGOS_AI_TIMEOUT_SECONDS deve ser positivo")
|
|
91
|
+
return cls(delays=delays, timeout=timeout)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
@dataclass(frozen=True)
|
|
95
|
+
class Attempt:
|
|
96
|
+
"""Uma tentativa que não terminou em sucesso: chave (``chave-N``), status e espera aplicada."""
|
|
97
|
+
|
|
98
|
+
key: str
|
|
99
|
+
status: int
|
|
100
|
+
wait: float = 0.0
|
|
101
|
+
|
|
102
|
+
def as_dict(self) -> dict[str, Any]:
|
|
103
|
+
return {"chave": self.key, "status": self.status, "espera": self.wait}
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def raw_attempts(attempts: Sequence[Attempt]) -> dict[str, Any]:
|
|
107
|
+
"""Campos de ``AIResponse.raw`` comuns a todos os providers (sem segredo)."""
|
|
108
|
+
return {
|
|
109
|
+
"key_rotations": [
|
|
110
|
+
{"chave": item.key, "motivo": str(item.status)} for item in attempts if item.status == RATE_LIMIT_STATUS
|
|
111
|
+
],
|
|
112
|
+
"attempts": [item.as_dict() for item in attempts],
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
class KeyRing:
|
|
117
|
+
"""Chaves em rodízio: cada chamada começa pela seguinte, para dividir o consumo das cotas."""
|
|
118
|
+
|
|
119
|
+
def __init__(self, keys: Sequence[str]) -> None:
|
|
120
|
+
self.keys = tuple(keys)
|
|
121
|
+
self._lock = threading.Lock()
|
|
122
|
+
self._next = 0
|
|
123
|
+
|
|
124
|
+
def __bool__(self) -> bool:
|
|
125
|
+
return bool(self.keys)
|
|
126
|
+
|
|
127
|
+
def order(self) -> list[tuple[int, str]]:
|
|
128
|
+
if not self.keys:
|
|
129
|
+
return [(0, "")]
|
|
130
|
+
with self._lock:
|
|
131
|
+
start = self._next % len(self.keys)
|
|
132
|
+
self._next += 1
|
|
133
|
+
count = len(self.keys)
|
|
134
|
+
return [((start + offset) % count, self.keys[(start + offset) % count]) for offset in range(count)]
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def error_status(exc: BaseException) -> int | None:
|
|
138
|
+
"""Código HTTP de um erro do ``urllib`` ou de SDK; 429 também quando o SDK só diz RESOURCE_EXHAUSTED."""
|
|
139
|
+
targets = (exc, getattr(exc, "response", None))
|
|
140
|
+
for target in targets:
|
|
141
|
+
for name in ("code", "status_code"):
|
|
142
|
+
value = getattr(target, name, None)
|
|
143
|
+
if isinstance(value, int) and not isinstance(value, bool):
|
|
144
|
+
return value
|
|
145
|
+
if isinstance(value, str) and value.isdigit():
|
|
146
|
+
return int(value)
|
|
147
|
+
if "RESOURCE_EXHAUSTED" in str(getattr(exc, "status", "") or "").upper():
|
|
148
|
+
return RATE_LIMIT_STATUS
|
|
149
|
+
return None
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _retry_after(exc: BaseException, now: Callable[[], float] = time.time) -> float | None:
|
|
153
|
+
for target in (exc, getattr(exc, "response", None)):
|
|
154
|
+
headers = getattr(target, "headers", None)
|
|
155
|
+
getter = getattr(headers, "get", None)
|
|
156
|
+
raw = getter("Retry-After") if callable(getter) else None
|
|
157
|
+
if raw:
|
|
158
|
+
return parse_retry_after(str(raw), now=now)
|
|
159
|
+
return None
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def parse_retry_after(value: str | None, *, now: Callable[[], float] = time.time) -> float | None:
|
|
163
|
+
raw = (value or "").strip()
|
|
164
|
+
if not raw:
|
|
165
|
+
return None
|
|
166
|
+
try:
|
|
167
|
+
return max(0.0, float(raw))
|
|
168
|
+
except ValueError:
|
|
169
|
+
pass
|
|
170
|
+
try:
|
|
171
|
+
moment = parsedate_to_datetime(raw)
|
|
172
|
+
except (TypeError, ValueError, IndexError, OverflowError):
|
|
173
|
+
return None
|
|
174
|
+
if moment.tzinfo is None:
|
|
175
|
+
moment = moment.replace(tzinfo=dt.timezone.utc)
|
|
176
|
+
return max(0.0, moment.timestamp() - now())
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _clean(text: str, secrets: Iterable[str]) -> str:
|
|
180
|
+
for secret in secrets:
|
|
181
|
+
if secret:
|
|
182
|
+
text = text.replace(secret, "[chave]")
|
|
183
|
+
return " ".join(text.split())[:DETAIL_LIMIT]
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _close(exc: BaseException) -> None:
|
|
187
|
+
closer = getattr(exc, "close", None)
|
|
188
|
+
if callable(closer):
|
|
189
|
+
try:
|
|
190
|
+
closer()
|
|
191
|
+
except Exception: # noqa: BLE001, S110 - liberar o corpo é só higiene
|
|
192
|
+
pass
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def describe_error(exc: BaseException, provider: str, secrets: Iterable[str] = ()) -> str:
|
|
196
|
+
"""Mensagem curta e sem segredo: corpo do HTTP, código/status do SDK ou só o tipo do erro."""
|
|
197
|
+
status = error_status(exc)
|
|
198
|
+
if isinstance(exc, urllib.error.HTTPError):
|
|
199
|
+
try:
|
|
200
|
+
body = _clean(exc.read().decode("utf-8", errors="replace"), secrets)
|
|
201
|
+
except Exception: # noqa: BLE001 - o corpo é só diagnóstico
|
|
202
|
+
body = ""
|
|
203
|
+
return f"provider {provider} respondeu HTTP {status}" + (f": {body}" if body else "")
|
|
204
|
+
if status is not None:
|
|
205
|
+
label = str(getattr(exc, "status", "") or "")
|
|
206
|
+
message = _clean(str(getattr(exc, "message", None) or exc), secrets)
|
|
207
|
+
head = " ".join(part for part in (str(status), label if not label.isdigit() else "") if part)
|
|
208
|
+
return f"falha no provider {provider}: {type(exc).__name__} {head}: {message}"
|
|
209
|
+
return f"falha de transporte no provider {provider}: {type(exc).__name__}"
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _service_error(exc: BaseException, provider: str, status: int | None, secrets: Iterable[str]) -> AIServiceError:
|
|
213
|
+
message = describe_error(exc, provider, secrets)
|
|
214
|
+
_close(exc)
|
|
215
|
+
return AIServiceError(
|
|
216
|
+
message,
|
|
217
|
+
http_status=status,
|
|
218
|
+
retryable=status is None or status == RATE_LIMIT_STATUS or status in TRANSIENT_STATUSES,
|
|
219
|
+
unknown=status is None,
|
|
220
|
+
)
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def call_with_keys(
|
|
224
|
+
send: Callable[[str], T],
|
|
225
|
+
ring: KeyRing,
|
|
226
|
+
*,
|
|
227
|
+
provider: str,
|
|
228
|
+
policy: ModelCallPolicy,
|
|
229
|
+
secrets: Iterable[str] = (),
|
|
230
|
+
on_event: Callable[[str], None] | None = None,
|
|
231
|
+
) -> tuple[T, tuple[Attempt, ...]]:
|
|
232
|
+
"""Executa ``send(chave)`` com a política do módulo; devolve ``(valor, tentativas que falharam)``.
|
|
233
|
+
|
|
234
|
+
``send`` pode levantar o erro nativo do SDK ou do ``urllib``; erros do Argos
|
|
235
|
+
(``AIServiceError``, ``InputValidationError``) passam sem alteração.
|
|
236
|
+
"""
|
|
237
|
+
secrets = tuple(secrets)
|
|
238
|
+
attempts: list[Attempt] = []
|
|
239
|
+
|
|
240
|
+
def notify(message: str) -> None:
|
|
241
|
+
if on_event is not None:
|
|
242
|
+
try:
|
|
243
|
+
on_event(message)
|
|
244
|
+
except Exception: # noqa: BLE001, S110 - aviso nunca derruba a chamada
|
|
245
|
+
pass
|
|
246
|
+
|
|
247
|
+
order = ring.order()
|
|
248
|
+
for position, (index, key) in enumerate(order):
|
|
249
|
+
label = f"chave-{index + 1}"
|
|
250
|
+
retries = 0
|
|
251
|
+
while True:
|
|
252
|
+
try:
|
|
253
|
+
return send(key), tuple(attempts)
|
|
254
|
+
except ArgosError:
|
|
255
|
+
raise
|
|
256
|
+
except Exception as exc: # noqa: BLE001 - SDKs e urllib levantam tipos variados
|
|
257
|
+
status = error_status(exc)
|
|
258
|
+
if status == RATE_LIMIT_STATUS:
|
|
259
|
+
_close(exc)
|
|
260
|
+
attempts.append(Attempt(label, status))
|
|
261
|
+
if position + 1 < len(order):
|
|
262
|
+
notify(f"{provider}: {label} recusou (429); usando a próxima chave")
|
|
263
|
+
break
|
|
264
|
+
if status in TRANSIENT_STATUSES and retries < len(policy.delays):
|
|
265
|
+
retry_after = _retry_after(exc)
|
|
266
|
+
wait = min(policy.max_wait, max(0.0, policy.delays[retries] if retry_after is None else retry_after))
|
|
267
|
+
_close(exc)
|
|
268
|
+
attempts.append(Attempt(label, status, wait))
|
|
269
|
+
retries += 1
|
|
270
|
+
notify(f"{provider}: HTTP {status}; nova tentativa em {wait:.0f}s ({retries}/{len(policy.delays)})")
|
|
271
|
+
policy.sleeper(wait)
|
|
272
|
+
continue
|
|
273
|
+
raise _service_error(exc, provider, status, secrets) from exc
|
|
274
|
+
raise AIServiceError(f"todas as chaves {provider} retornaram 429", http_status=RATE_LIMIT_STATUS, retryable=True)
|