perucompras-cli 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. perucompras_cli-0.1.0.dist-info/METADATA +429 -0
  2. perucompras_cli-0.1.0.dist-info/RECORD +50 -0
  3. perucompras_cli-0.1.0.dist-info/WHEEL +4 -0
  4. perucompras_cli-0.1.0.dist-info/entry_points.txt +2 -0
  5. perucompras_cli-0.1.0.dist-info/licenses/LICENSE +16 -0
  6. piloto_ai_cli/__init__.py +51 -0
  7. piloto_ai_cli/__main__.py +5 -0
  8. piloto_ai_cli/api.py +394 -0
  9. piloto_ai_cli/attribute_text.py +106 -0
  10. piloto_ai_cli/attributes_service.py +250 -0
  11. piloto_ai_cli/auto_tag.py +65 -0
  12. piloto_ai_cli/backoff.py +25 -0
  13. piloto_ai_cli/cards.py +871 -0
  14. piloto_ai_cli/cli.py +602 -0
  15. piloto_ai_cli/connectors.py +106 -0
  16. piloto_ai_cli/database.py +491 -0
  17. piloto_ai_cli/enrichment.py +557 -0
  18. piloto_ai_cli/errors.py +92 -0
  19. piloto_ai_cli/excel.py +186 -0
  20. piloto_ai_cli/extraction.py +1316 -0
  21. piloto_ai_cli/health.py +398 -0
  22. piloto_ai_cli/health_workflow.py +1060 -0
  23. piloto_ai_cli/http_client.py +610 -0
  24. piloto_ai_cli/llm_client.py +259 -0
  25. piloto_ai_cli/llm_extraction.py +444 -0
  26. piloto_ai_cli/llm_output.py +90 -0
  27. piloto_ai_cli/pane.py +303 -0
  28. piloto_ai_cli/parsers.py +477 -0
  29. piloto_ai_cli/payload_store.py +227 -0
  30. piloto_ai_cli/pdf_parser.py +12 -0
  31. piloto_ai_cli/py.typed +0 -0
  32. piloto_ai_cli/query_compiler.py +1112 -0
  33. piloto_ai_cli/query_result.py +175 -0
  34. piloto_ai_cli/query_service.py +199 -0
  35. piloto_ai_cli/reextract.py +129 -0
  36. piloto_ai_cli/review.py +217 -0
  37. piloto_ai_cli/rules.py +67 -0
  38. piloto_ai_cli/run_log.py +230 -0
  39. piloto_ai_cli/schema/__init__.py +25 -0
  40. piloto_ai_cli/schema/contract-v1.schema.json +261 -0
  41. piloto_ai_cli/schema/contract.py +257 -0
  42. piloto_ai_cli/schema/migration_filters.py +59 -0
  43. piloto_ai_cli/schema/models.py +747 -0
  44. piloto_ai_cli/schema/snowflake_autogen.py +134 -0
  45. piloto_ai_cli/search_form.py +82 -0
  46. piloto_ai_cli/settings.py +174 -0
  47. piloto_ai_cli/snowflake_url.py +90 -0
  48. piloto_ai_cli/stamp_service.py +53 -0
  49. piloto_ai_cli/sync.py +1157 -0
  50. piloto_ai_cli/unit_converter.py +81 -0
@@ -0,0 +1,259 @@
1
+ """Anthropic connector routed through the durable HTTP request logger."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from collections.abc import AsyncGenerator, Mapping
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
9
+ from typing import Any, cast
10
+
11
+ import httpx2
12
+ from anthropic import (
13
+ APIConnectionError,
14
+ APIStatusError,
15
+ AsyncAnthropic,
16
+ AuthenticationError,
17
+ PermissionDeniedError,
18
+ )
19
+
20
+ from piloto_ai_cli.http_client import HttpClient, logged_request_id
21
+ from piloto_ai_cli.settings import Settings
22
+
23
+ MAX_OUTPUT_TOKENS = 4096
24
+ SNOWFLAKE_TOKEN_TYPE_HEADER = "X-Snowflake-Authorization-Token-Type"
25
+
26
+
27
+ class LLMRequestError(Exception):
28
+ """A logged LLM request failed; ``request_id`` points at its stored response."""
29
+
30
+ def __init__(self, message: str, request_id: str) -> None:
31
+ super().__init__(message)
32
+ self.request_id = request_id
33
+
34
+
35
+ class LLMConfigurationError(Exception):
36
+ """The LLM provider cannot be used as configured.
37
+
38
+ Not a failure of the ficha being extracted: every later request would
39
+ fail the same way, so callers stop the run instead of recording it
40
+ against the ficha.
41
+ """
42
+
43
+
44
+ class SPCSSessionTokenError(LLMConfigurationError, RuntimeError):
45
+ """The SPCS session token file is missing, unreadable or empty."""
46
+
47
+
48
+ class LLMCredentialError(LLMRequestError, LLMConfigurationError):
49
+ """The provider rejected the configured credential (HTTP 401 or 403).
50
+
51
+ A configuration error, not a failure of the ficha being extracted: every
52
+ later request would fail the same way, so callers stop the run instead of
53
+ recording it against the ficha.
54
+ """
55
+
56
+
57
+ @dataclass(frozen=True)
58
+ class LLMResponse:
59
+ """Text and usage from one logged LLM request."""
60
+
61
+ text: str
62
+ input_tokens: int
63
+ output_tokens: int
64
+ request_id: str
65
+
66
+
67
+ class _WriteRequestTransport(httpx2.AsyncBaseTransport):
68
+ """Route the SDK's requests through the logging client's ``write_request()``.
69
+
70
+ Both sides use ``httpx2``, so its responses and transport errors (each
71
+ tagged with its logged request ID) are handed to the SDK as they are.
72
+ """
73
+
74
+ def __init__(self, http_client: HttpClient, timeout: float) -> None:
75
+ self._http_client = http_client
76
+ self._timeout = timeout
77
+
78
+ async def handle_async_request(self, request: httpx2.Request) -> httpx2.Response:
79
+ body = await request.aread()
80
+ try:
81
+ request_data = json.loads(body) if body else {}
82
+ except (UnicodeDecodeError, json.JSONDecodeError) as error:
83
+ raise ValueError("Anthropic request body must be valid JSON") from error
84
+ if not isinstance(request_data, dict):
85
+ raise ValueError("Anthropic request body must be a JSON object")
86
+
87
+ response = await self._http_client.write_request(
88
+ request.method,
89
+ str(request.url),
90
+ endpoint="post_llm",
91
+ headers=request.headers,
92
+ content=body,
93
+ timeout=self._timeout,
94
+ log_data=cast(Mapping[str, Any], request_data),
95
+ )
96
+ if not isinstance(response.extensions.get("request_id"), str):
97
+ raise RuntimeError("LLM request was not logged")
98
+ return response
99
+
100
+
101
+ def _read_spcs_session_token(token_path: Path) -> str:
102
+ try:
103
+ token = token_path.read_text(encoding="utf-8").strip()
104
+ except (OSError, UnicodeDecodeError) as error:
105
+ raise SPCSSessionTokenError(
106
+ f"could not read the SPCS session token from {token_path}"
107
+ ) from error
108
+ if not token:
109
+ raise SPCSSessionTokenError(f"the SPCS session token at {token_path} is empty")
110
+ return token
111
+
112
+
113
+ class _SPCSSessionTokenAuth(httpx2.Auth):
114
+ """Send the SPCS session token, re-read on every request (SPCS refreshes it)."""
115
+
116
+ def __init__(self, token_path: Path) -> None:
117
+ self._token_path = token_path
118
+
119
+ async def async_auth_flow(
120
+ self, request: httpx2.Request
121
+ ) -> AsyncGenerator[httpx2.Request, httpx2.Response]:
122
+ token = _read_spcs_session_token(self._token_path)
123
+ request.headers["Authorization"] = f"Bearer {token}"
124
+ request.headers[SNOWFLAKE_TOKEN_TYPE_HEADER] = "OAUTH"
125
+ yield request
126
+
127
+
128
+ def _required_api_key(settings: Settings) -> str:
129
+ if settings.llm_api_key is None or not settings.llm_api_key.get_secret_value().strip():
130
+ raise ValueError("llm_api_key must be configured")
131
+ return settings.llm_api_key.get_secret_value()
132
+
133
+
134
+ class LLMClient:
135
+ """Make one LLM request at a time through the configured HTTP client.
136
+
137
+ ``anthropic`` calls the Claude API with ``llm_api_key``. ``snowflake`` calls
138
+ the Cortex Messages endpoint (``https://<host>/api/v2/cortex``), which takes
139
+ the same requests: inside SPCS with the service's session token, elsewhere
140
+ with a PAT in ``llm_api_key``. Either way every request goes through
141
+ ``write_request()``.
142
+ """
143
+
144
+ def __init__(self, settings: Settings, http_client: HttpClient) -> None:
145
+ timeout = settings.llm_timeout_seconds
146
+ auth: httpx2.Auth | None = None
147
+ match settings.llm_provider:
148
+ case "anthropic":
149
+ credentials: dict[str, Any] = {"api_key": _required_api_key(settings)}
150
+ self._credential_hint = "check PILOTO_LLM_API_KEY"
151
+ case "snowflake":
152
+ host = settings.llm_snowflake_host
153
+ if not host:
154
+ raise ValueError("llm_snowflake_host must be configured")
155
+ base_url = f"https://{host}/api/v2/cortex"
156
+ if settings.llm_snowflake_auth == "spcs_oauth":
157
+ # Fail fast: check the token before the command sends any
158
+ # request; the auth flow still re-reads it on every call.
159
+ _read_spcs_session_token(settings.llm_snowflake_token_path)
160
+ # The SDK requires a credential; the auth flow replaces it.
161
+ credentials = {"auth_token": "spcs-session-token", "base_url": base_url}
162
+ auth = _SPCSSessionTokenAuth(settings.llm_snowflake_token_path)
163
+ self._credential_hint = (
164
+ "check the service role's Cortex grants and PILOTO_LLM_MODEL"
165
+ )
166
+ else:
167
+ credentials = {
168
+ "auth_token": _required_api_key(settings),
169
+ "base_url": base_url,
170
+ }
171
+ self._credential_hint = (
172
+ "check the PAT in PILOTO_LLM_API_KEY and its role's Cortex grants"
173
+ )
174
+ case _:
175
+ raise ValueError(f"unsupported LLM provider: {settings.llm_provider}")
176
+
177
+ sdk_http_client = httpx2.AsyncClient(
178
+ transport=_WriteRequestTransport(http_client, timeout),
179
+ timeout=timeout,
180
+ auth=auth,
181
+ )
182
+ self._client = AsyncAnthropic(
183
+ **credentials,
184
+ max_retries=0,
185
+ timeout=timeout,
186
+ http_client=sdk_http_client,
187
+ )
188
+ self._model = settings.llm_model
189
+ self._provider: str = settings.llm_provider
190
+
191
+ @property
192
+ def provider(self) -> str:
193
+ """The configured provider (``anthropic`` or ``snowflake``) this client calls."""
194
+ return self._provider
195
+
196
+ async def __aenter__(self) -> LLMClient:
197
+ return self
198
+
199
+ async def __aexit__(
200
+ self,
201
+ exc_type: type[BaseException] | None,
202
+ exc: BaseException | None,
203
+ traceback: object | None,
204
+ ) -> None:
205
+ await self.aclose()
206
+
207
+ async def aclose(self) -> None:
208
+ await self._client.close()
209
+
210
+ async def post_llm(self, prompt: str) -> LLMResponse:
211
+ """Send one prompt and return its text, usage, and durable request ID."""
212
+ try:
213
+ response = await self._client.messages.with_raw_response.create(
214
+ model=self._model,
215
+ max_tokens=MAX_OUTPUT_TOKENS,
216
+ messages=[{"role": "user", "content": prompt}],
217
+ )
218
+ except APIStatusError as error:
219
+ failed_id = error.response.extensions.get("request_id")
220
+ if not isinstance(failed_id, str):
221
+ raise
222
+ if isinstance(error, (AuthenticationError, PermissionDeniedError)):
223
+ raise LLMCredentialError(
224
+ f"LLM provider rejected the credential (HTTP {error.status_code}); "
225
+ f"{self._credential_hint}: {error}",
226
+ failed_id,
227
+ ) from error
228
+ raise LLMRequestError(f"LLM request failed: {error}", failed_id) from error
229
+ except APIConnectionError as error:
230
+ if isinstance(error.__cause__, SPCSSessionTokenError):
231
+ # Raised by the auth flow before any request was sent.
232
+ raise error.__cause__ from None
233
+ # Timeouts and connection failures: the SDK chains the transport
234
+ # error that ``write_request()`` logged and tagged with its ID.
235
+ failed_id = logged_request_id(error.__cause__) if error.__cause__ is not None else None
236
+ if failed_id is None:
237
+ raise
238
+ raise LLMRequestError(f"LLM request failed: {error}", failed_id) from error
239
+ request_id = response.http_response.extensions.get("request_id")
240
+ if not isinstance(request_id, str):
241
+ raise RuntimeError("LLM request was not logged")
242
+ try:
243
+ message = await response.parse()
244
+ # Non-strict SDK models accept wrong-schema JSON (e.g. ``content`` or
245
+ # ``usage`` set to null), so extraction can fail too: keep it inside
246
+ # the boundary so the caller always gets the logged request ID.
247
+ text = "".join(block.text for block in message.content if block.type == "text")
248
+ input_tokens = message.usage.input_tokens
249
+ output_tokens = message.usage.output_tokens
250
+ except (ValueError, TypeError, AttributeError) as error:
251
+ raise LLMRequestError(
252
+ f"LLM response could not be parsed: {error}", request_id
253
+ ) from error
254
+ return LLMResponse(
255
+ text=text,
256
+ input_tokens=input_tokens,
257
+ output_tokens=output_tokens,
258
+ request_id=request_id,
259
+ )