abintegro 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.
- abintegro/__init__.py +156 -0
- abintegro/__main__.py +16 -0
- abintegro/ai.py +543 -0
- abintegro/audit.py +227 -0
- abintegro/bi.py +667 -0
- abintegro/catalog.py +231 -0
- abintegro/cli.py +1122 -0
- abintegro/config.py +653 -0
- abintegro/connector.py +2527 -0
- abintegro/credentials.py +724 -0
- abintegro/ctx.py +818 -0
- abintegro/errors.py +391 -0
- abintegro/guardrails.py +200 -0
- abintegro/lookup.py +164 -0
- abintegro/manifest.py +474 -0
- abintegro/notifications.py +641 -0
- abintegro/policy.py +169 -0
- abintegro/probe.py +183 -0
- abintegro/py.typed +0 -0
- abintegro/queue.py +216 -0
- abintegro/runner.py +1580 -0
- abintegro/service.py +474 -0
- abintegro/state.py +124 -0
- abintegro/store.py +330 -0
- abintegro/suggestion.py +687 -0
- abintegro/task.py +118 -0
- abintegro/tenant_secret.py +781 -0
- abintegro/testing.py +112 -0
- abintegro/warehouse.py +573 -0
- abintegro/webhooks.py +338 -0
- abintegro-0.1.0.dist-info/METADATA +112 -0
- abintegro-0.1.0.dist-info/RECORD +52 -0
- abintegro-0.1.0.dist-info/WHEEL +5 -0
- abintegro-0.1.0.dist-info/entry_points.txt +2 -0
- abintegro-0.1.0.dist-info/licenses/LICENSE +202 -0
- abintegro-0.1.0.dist-info/top_level.txt +2 -0
- abintegro_ai/__init__.py +108 -0
- abintegro_ai/decisions.py +605 -0
- abintegro_ai/errors.py +38 -0
- abintegro_ai/loop.py +125 -0
- abintegro_ai/metric.py +100 -0
- abintegro_ai/providers/__init__.py +237 -0
- abintegro_ai/providers/_http.py +70 -0
- abintegro_ai/providers/anthropic.py +247 -0
- abintegro_ai/providers/openai.py +237 -0
- abintegro_ai/providers/vertex.py +420 -0
- abintegro_ai/py.typed +0 -0
- abintegro_ai/report.py +272 -0
- abintegro_ai/retry.py +43 -0
- abintegro_ai/schema.py +229 -0
- abintegro_ai/thinking.py +142 -0
- abintegro_ai/types.py +130 -0
abintegro/ai.py
ADDED
|
@@ -0,0 +1,543 @@
|
|
|
1
|
+
"""``ctx.ai(prompt, **settings)`` — one AI call, inside a task.
|
|
2
|
+
|
|
3
|
+
The model is *called by* a task and never decides control flow: classify or
|
|
4
|
+
extract, never "what next". So it is offered no tool, not even to shape its
|
|
5
|
+
answer: a response schema goes as each provider's own structured format. It may
|
|
6
|
+
not emit facts either — numbers come from connectors — so a schema is the normal case.
|
|
7
|
+
|
|
8
|
+
What a task does with it::
|
|
9
|
+
|
|
10
|
+
# Read text into a shape. A pydantic model is the normal case; ``parsed`` is one.
|
|
11
|
+
triage = await ctx.ai(f"Classify this enquiry:\n{body}", response_schema=Triage)
|
|
12
|
+
if triage.parsed.urgent:
|
|
13
|
+
...
|
|
14
|
+
|
|
15
|
+
# Go on from an earlier answer: its conversation is the history of the next.
|
|
16
|
+
reply = await ctx.ai("Draft a short reply to it in Slovene.", history=triage.conversation)
|
|
17
|
+
|
|
18
|
+
# Write text. Thinking is low unless asked: off, minimal, low, medium, high.
|
|
19
|
+
note = await ctx.ai(f"Summarise for the course leader:\n{facts}", thinking="medium")
|
|
20
|
+
note.text
|
|
21
|
+
|
|
22
|
+
An answer that is empty, cut off, or not in the schema's shape raises
|
|
23
|
+
``AiNoAnswer``. A conversation is plain text, so it can wait in ``ctx.state``
|
|
24
|
+
for a later run, and it carries no ``system_instruction``: pass it again.
|
|
25
|
+
|
|
26
|
+
A call names a provider and a model (``config_globals/models``). The providers
|
|
27
|
+
are ``abintegro_ai``'s, the code the app's chat runs on too:
|
|
28
|
+
|
|
29
|
+
* ``vertex`` — Vertex AI in the tenant's own project, as the service's identity.
|
|
30
|
+
* ``vertex_api_key``, ``gemini`` (Google AI Studio), ``anthropic``, ``openai``,
|
|
31
|
+
``langdock`` — the key in the tenant secret's ``ai_{type}`` entry, billed to
|
|
32
|
+
whoever owns the key.
|
|
33
|
+
|
|
34
|
+
A provider with locations is called at the tenant's. Tokens are counted per run
|
|
35
|
+
against ``max_tokens`` and audited.
|
|
36
|
+
|
|
37
|
+
``ctx.decide(text, **questions)`` asks fixed-outcome questions about one text
|
|
38
|
+
and returns probabilities (:class:`Decision`): through Google's Decisions API
|
|
39
|
+
for a Gemini Decision model, through a prompt on any other model.
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
from __future__ import annotations
|
|
43
|
+
|
|
44
|
+
import dataclasses
|
|
45
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
46
|
+
from types import SimpleNamespace
|
|
47
|
+
from typing import TYPE_CHECKING, Any, Literal
|
|
48
|
+
|
|
49
|
+
from pydantic import BaseModel, Field
|
|
50
|
+
|
|
51
|
+
from abintegro_ai import Message, Provider, Request
|
|
52
|
+
from abintegro_ai.decisions import (
|
|
53
|
+
Answer,
|
|
54
|
+
Decider,
|
|
55
|
+
DecisionRequest,
|
|
56
|
+
GeminiDecisions,
|
|
57
|
+
PromptedDecisions,
|
|
58
|
+
Question,
|
|
59
|
+
decision_method,
|
|
60
|
+
)
|
|
61
|
+
from abintegro_ai.providers import (
|
|
62
|
+
API_KEY_FIELD,
|
|
63
|
+
PROVIDER_TYPES,
|
|
64
|
+
VertexProvider,
|
|
65
|
+
build_provider,
|
|
66
|
+
capabilities,
|
|
67
|
+
client_kwargs,
|
|
68
|
+
genai_client,
|
|
69
|
+
)
|
|
70
|
+
from abintegro_ai.providers.vertex import vertex_model
|
|
71
|
+
from abintegro_ai.thinking import gemini_version, level
|
|
72
|
+
|
|
73
|
+
from .audit import AuditLog, digest
|
|
74
|
+
from .config import AI_PROVIDERS, DEFAULT_RUNTIME_MODEL, RunnerConfig
|
|
75
|
+
from .errors import (
|
|
76
|
+
AiNoAnswer,
|
|
77
|
+
AiNoDecision,
|
|
78
|
+
ConfigurationError,
|
|
79
|
+
SecretConnectorMissing,
|
|
80
|
+
SecretFieldMissing,
|
|
81
|
+
SecretMissing,
|
|
82
|
+
)
|
|
83
|
+
from .guardrails import GuardrailState
|
|
84
|
+
from .tenant_secret import ai_entry, fingerprint
|
|
85
|
+
|
|
86
|
+
if TYPE_CHECKING:
|
|
87
|
+
import httpx
|
|
88
|
+
|
|
89
|
+
from .credentials import CredentialBroker
|
|
90
|
+
|
|
91
|
+
__all__ = ["MIN_OUTPUT_TOKENS", "AiClient", "AiResult", "AiTurn", "Decision", "vertex_model"]
|
|
92
|
+
|
|
93
|
+
#: Unless a task asks otherwise (``thinking=``): Gemini 3 at LOW, Gemini 2.5 on a
|
|
94
|
+
#: 1024-token budget, Claude and OpenAI's reasoning models at low effort.
|
|
95
|
+
THINKING = "low"
|
|
96
|
+
|
|
97
|
+
#: Thinking is billed against ``max_output_tokens``, so a limit sized for the
|
|
98
|
+
#: answer alone ends in MAX_TOKENS with nothing to show. Smaller asks are raised.
|
|
99
|
+
MIN_OUTPUT_TOKENS = 4096
|
|
100
|
+
|
|
101
|
+
_VERTEX = ("vertex", "vertex_api_key")
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
class AiTurn(BaseModel):
|
|
105
|
+
"""One turn of a ``ctx.ai`` conversation: what was asked, or what the model answered.
|
|
106
|
+
|
|
107
|
+
Plain text, so a conversation can go to another model, or wait in ``ctx.state``.
|
|
108
|
+
"""
|
|
109
|
+
|
|
110
|
+
model_config = {"frozen": True}
|
|
111
|
+
|
|
112
|
+
role: Literal["user", "assistant"]
|
|
113
|
+
text: str = Field(min_length=1)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
class AiResult(BaseModel):
|
|
117
|
+
"""What ``ctx.ai`` returns. ``parsed`` is filled when a schema was given."""
|
|
118
|
+
|
|
119
|
+
text: str
|
|
120
|
+
#: The answer read against ``response_schema``: the pydantic model, or a dict.
|
|
121
|
+
parsed: Any = None
|
|
122
|
+
#: The turns so far, this question and answer last. Pass it as ``history`` to go on.
|
|
123
|
+
conversation: list[AiTurn] = Field(default_factory=list)
|
|
124
|
+
model: str
|
|
125
|
+
input_tokens: int
|
|
126
|
+
#: The answer and the thinking.
|
|
127
|
+
output_tokens: int
|
|
128
|
+
#: The part of ``input_tokens`` served from the context cache.
|
|
129
|
+
cached_tokens: int = 0
|
|
130
|
+
#: The part of ``output_tokens`` spent thinking, where the model reports it.
|
|
131
|
+
thinking_tokens: int = 0
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
class Decision:
|
|
135
|
+
"""What ``ctx.decide`` returns: each question's answer by its name.
|
|
136
|
+
|
|
137
|
+
``decision.urgent`` and ``decision["urgent"]`` are the same answer. A
|
|
138
|
+
``YesNoAnswer`` has ``yes``, ``probability`` and ``confidence``; a
|
|
139
|
+
``ChoiceAnswer`` ``choice``; a ``ScoreAnswer`` ``score`` and ``level``; both
|
|
140
|
+
also ``probabilities``. ``calibrated`` is true only for the Decisions API.
|
|
141
|
+
"""
|
|
142
|
+
|
|
143
|
+
#: Names a question may not take: they are this object's own.
|
|
144
|
+
RESERVED = frozenset(
|
|
145
|
+
{
|
|
146
|
+
"answers",
|
|
147
|
+
"model",
|
|
148
|
+
"provider",
|
|
149
|
+
"method",
|
|
150
|
+
"calibrated",
|
|
151
|
+
"input_tokens",
|
|
152
|
+
"output_tokens",
|
|
153
|
+
"thinking_tokens",
|
|
154
|
+
}
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
def __init__(
|
|
158
|
+
self,
|
|
159
|
+
answers: Mapping[str, Answer],
|
|
160
|
+
*,
|
|
161
|
+
model: str,
|
|
162
|
+
provider: str,
|
|
163
|
+
method: str,
|
|
164
|
+
calibrated: bool,
|
|
165
|
+
input_tokens: int,
|
|
166
|
+
output_tokens: int,
|
|
167
|
+
thinking_tokens: int,
|
|
168
|
+
) -> None:
|
|
169
|
+
self.answers = dict(answers)
|
|
170
|
+
self.model = model
|
|
171
|
+
self.provider = provider
|
|
172
|
+
self.method = method
|
|
173
|
+
self.calibrated = calibrated
|
|
174
|
+
self.input_tokens = input_tokens
|
|
175
|
+
#: The answer and the thinking; the Decisions API writes none.
|
|
176
|
+
self.output_tokens = output_tokens
|
|
177
|
+
self.thinking_tokens = thinking_tokens
|
|
178
|
+
|
|
179
|
+
def __getattr__(self, name: str) -> Answer:
|
|
180
|
+
answers = self.__dict__.get("answers") or {}
|
|
181
|
+
if name in answers:
|
|
182
|
+
return answers[name]
|
|
183
|
+
raise AttributeError(f"this decision asked no question named {name!r}")
|
|
184
|
+
|
|
185
|
+
def __getitem__(self, name: str) -> Answer:
|
|
186
|
+
return self.answers[name]
|
|
187
|
+
|
|
188
|
+
def __repr__(self) -> str:
|
|
189
|
+
return f"Decision({self.answers!r}, model={self.model!r}, method={self.method!r})"
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def _asked(text: str, questions: Mapping[str, Question]) -> dict[str, Any]:
|
|
193
|
+
"""What a decision asked, for its audit hash."""
|
|
194
|
+
return {
|
|
195
|
+
"text": text,
|
|
196
|
+
"questions": {
|
|
197
|
+
key: {"type": type(question).__name__, **dataclasses.asdict(question)}
|
|
198
|
+
for key, question in questions.items()
|
|
199
|
+
},
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _turns(history: Sequence[AiTurn | dict[str, Any]] | None) -> list[AiTurn]:
|
|
204
|
+
"""An earlier ``conversation``, also as read back from ``ctx.state``."""
|
|
205
|
+
try:
|
|
206
|
+
return [AiTurn.model_validate(turn) for turn in history or []]
|
|
207
|
+
except ValueError as error:
|
|
208
|
+
raise ValueError(
|
|
209
|
+
"ctx.ai history is an earlier result's conversation: turns of role user or "
|
|
210
|
+
f"assistant, each with text ({error})"
|
|
211
|
+
) from None
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
class _TransportClient:
|
|
215
|
+
"""google-genai's ``aio.models`` surface over a test's ``transport``."""
|
|
216
|
+
|
|
217
|
+
def __init__(self, transport: Any, *, location: str, provider: str) -> None:
|
|
218
|
+
self._transport = transport
|
|
219
|
+
self._location = location
|
|
220
|
+
self._provider = provider
|
|
221
|
+
self.aio = SimpleNamespace(models=self)
|
|
222
|
+
|
|
223
|
+
async def generate_content(self, *, model: str, contents: Any, config: Any) -> Any:
|
|
224
|
+
return await self._transport(
|
|
225
|
+
model, contents, config, location=self._location, provider=self._provider
|
|
226
|
+
)
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
class AiClient:
|
|
230
|
+
"""The runner's rules around one model call: which provider, whose key, what is audited.
|
|
231
|
+
|
|
232
|
+
``transport`` stands in for Vertex AI's ``generate_content`` and
|
|
233
|
+
``client_factory`` for ``google.genai.Client``; ``http_transport`` for the
|
|
234
|
+
providers spoken over plain HTTP.
|
|
235
|
+
"""
|
|
236
|
+
|
|
237
|
+
def __init__(
|
|
238
|
+
self,
|
|
239
|
+
config: RunnerConfig,
|
|
240
|
+
audit: AuditLog,
|
|
241
|
+
*,
|
|
242
|
+
credentials: CredentialBroker | None = None,
|
|
243
|
+
transport: Any = None,
|
|
244
|
+
client_factory: Callable[..., Any] | None = None,
|
|
245
|
+
http_transport: httpx.AsyncBaseTransport | None = None,
|
|
246
|
+
) -> None:
|
|
247
|
+
self._config = config
|
|
248
|
+
self._audit = audit
|
|
249
|
+
self._credentials = credentials
|
|
250
|
+
self._transport = transport
|
|
251
|
+
self._client_factory = client_factory or genai_client
|
|
252
|
+
self._http_transport = http_transport
|
|
253
|
+
#: ``(provider, location) → (key fingerprint, provider)``: the location
|
|
254
|
+
#: picks the endpoint, and a new key replaces the provider built on the old.
|
|
255
|
+
self._providers: dict[tuple[str, str], tuple[str, Provider]] = {}
|
|
256
|
+
|
|
257
|
+
def _client(self, provider: str, location: str, api_key: str | None) -> Any:
|
|
258
|
+
"""A google-genai client for one of the two Vertex AI types."""
|
|
259
|
+
return self._client_factory(
|
|
260
|
+
**client_kwargs(location, project=self._config.project_id, api_key=api_key)
|
|
261
|
+
)
|
|
262
|
+
|
|
263
|
+
def _provider(self, provider: str, location: str | None, api_key: str | None) -> Provider:
|
|
264
|
+
held = fingerprint(api_key) if api_key else ""
|
|
265
|
+
cached = self._providers.get((provider, location or ""))
|
|
266
|
+
if cached is not None and cached[0] == held:
|
|
267
|
+
return cached[1]
|
|
268
|
+
built: Provider
|
|
269
|
+
if provider in _VERTEX:
|
|
270
|
+
assert location is not None
|
|
271
|
+
if self._transport is not None:
|
|
272
|
+
client = _TransportClient(self._transport, location=location, provider=provider)
|
|
273
|
+
else:
|
|
274
|
+
try:
|
|
275
|
+
client = self._client(provider, location, api_key)
|
|
276
|
+
except Exception as error: # reported, not swallowed
|
|
277
|
+
# The type only for a keyed client: its error could quote the key.
|
|
278
|
+
reason = type(error).__name__ if api_key else str(error)
|
|
279
|
+
raise ConfigurationError(
|
|
280
|
+
f"Vertex AI is not reachable from this process ({provider}): {reason}. "
|
|
281
|
+
f"It needs aiplatform.googleapis.com enabled in the project that pays "
|
|
282
|
+
f"for the calls."
|
|
283
|
+
) from (None if api_key else error)
|
|
284
|
+
built = VertexProvider(provider, client=client)
|
|
285
|
+
else:
|
|
286
|
+
built = build_provider(
|
|
287
|
+
provider, location=location, api_key=api_key, transport=self._http_transport
|
|
288
|
+
)
|
|
289
|
+
self._providers[(provider, location or "")] = (held, built)
|
|
290
|
+
return built
|
|
291
|
+
|
|
292
|
+
async def _api_key(self, provider: str) -> str:
|
|
293
|
+
"""The provider's key from the tenant secret. Never a fallback to another provider."""
|
|
294
|
+
entry = ai_entry(provider)
|
|
295
|
+
try:
|
|
296
|
+
if self._credentials is None:
|
|
297
|
+
raise SecretMissing(self._config.secret_id, self._config.project_id)
|
|
298
|
+
return await self._credentials.secret(entry, API_KEY_FIELD)
|
|
299
|
+
except (SecretMissing, SecretConnectorMissing, SecretFieldMissing):
|
|
300
|
+
raise ConfigurationError(
|
|
301
|
+
f"ctx.ai calls AI provider {provider!r}, and the tenant secret holds no "
|
|
302
|
+
f"{entry}.{API_KEY_FIELD}. Save the key with the provider in the app; the call "
|
|
303
|
+
f"does not fall back to another provider."
|
|
304
|
+
) from None
|
|
305
|
+
|
|
306
|
+
@staticmethod
|
|
307
|
+
def _location(provider: str, location: str | None) -> str | None:
|
|
308
|
+
kind = PROVIDER_TYPES[provider]
|
|
309
|
+
if not kind.locations:
|
|
310
|
+
return None
|
|
311
|
+
where = location or kind.default_location
|
|
312
|
+
if where not in kind.locations:
|
|
313
|
+
what = "a Vertex AI multi-region" if provider in _VERTEX else f"a {kind.label} region"
|
|
314
|
+
raise ConfigurationError(
|
|
315
|
+
f"the {provider} provider's location is {where!r}; ctx.ai takes {what}: "
|
|
316
|
+
f"{', '.join(kind.locations)}"
|
|
317
|
+
)
|
|
318
|
+
return where
|
|
319
|
+
|
|
320
|
+
async def generate(
|
|
321
|
+
self,
|
|
322
|
+
prompt: str,
|
|
323
|
+
*,
|
|
324
|
+
history: Sequence[AiTurn | dict[str, Any]] | None = None,
|
|
325
|
+
model: str | None = None,
|
|
326
|
+
provider: str = "vertex",
|
|
327
|
+
location: str | None = None,
|
|
328
|
+
response_schema: type[BaseModel] | dict[str, Any] | None = None,
|
|
329
|
+
temperature: float | None = None,
|
|
330
|
+
thinking: str | None = THINKING,
|
|
331
|
+
max_output_tokens: int = 8192,
|
|
332
|
+
system_instruction: str | None = None,
|
|
333
|
+
run_id: str | None = None,
|
|
334
|
+
task_id: str | None = None,
|
|
335
|
+
step_id: str | None = None,
|
|
336
|
+
guardrails: GuardrailState | None = None,
|
|
337
|
+
) -> AiResult:
|
|
338
|
+
"""``prompt`` after ``history``, an earlier result's ``conversation``.
|
|
339
|
+
|
|
340
|
+
``history`` carries the turns only: a ``system_instruction`` is given
|
|
341
|
+
again with each call that needs it. ``thinking`` is ``off``, ``minimal``,
|
|
342
|
+
``low``, ``medium`` or ``high`` on every provider, ``None`` the model's default.
|
|
343
|
+
"""
|
|
344
|
+
if not prompt.strip():
|
|
345
|
+
raise ValueError("ctx.ai needs a prompt")
|
|
346
|
+
thinking = level(thinking)
|
|
347
|
+
turns = _turns(history)
|
|
348
|
+
chosen = model or DEFAULT_RUNTIME_MODEL
|
|
349
|
+
if provider not in AI_PROVIDERS:
|
|
350
|
+
raise ConfigurationError(
|
|
351
|
+
f"{provider!r} is not an AI provider type; ctx.ai calls {', '.join(AI_PROVIDERS)}"
|
|
352
|
+
)
|
|
353
|
+
if not capabilities(provider, chosen).text:
|
|
354
|
+
raise ConfigurationError(
|
|
355
|
+
f"{chosen} answers decisions and writes no text: ctx.ai cannot call it. "
|
|
356
|
+
f"Ask it with ctx.decide, or give ctx.ai a text model."
|
|
357
|
+
)
|
|
358
|
+
where = self._location(provider, location)
|
|
359
|
+
# Before anything is sent: a role on a provider with no key fails here.
|
|
360
|
+
api_key = await self._api_key(provider) if PROVIDER_TYPES[provider].keyed else None
|
|
361
|
+
|
|
362
|
+
sent_max = max(max_output_tokens, MIN_OUTPUT_TOKENS)
|
|
363
|
+
# Gemini 3 is tuned for its own default temperature, and can loop below
|
|
364
|
+
# it; older Gemini models are pinned to 0 for repeatable answers. Other
|
|
365
|
+
# models keep theirs: newer Claude models refuse a temperature.
|
|
366
|
+
version = gemini_version(chosen)
|
|
367
|
+
if temperature is None and version is not None and version < (3, 0):
|
|
368
|
+
temperature = 0.0
|
|
369
|
+
request = Request(
|
|
370
|
+
model=chosen,
|
|
371
|
+
messages=[Message(turn.role, turn.text) for turn in turns] + [Message("user", prompt)],
|
|
372
|
+
system=system_instruction,
|
|
373
|
+
max_output_tokens=sent_max,
|
|
374
|
+
temperature=temperature,
|
|
375
|
+
thinking=thinking,
|
|
376
|
+
response_schema=response_schema,
|
|
377
|
+
)
|
|
378
|
+
reply = await self._provider(provider, where, api_key).generate(request)
|
|
379
|
+
usage = reply.usage
|
|
380
|
+
output_tokens = usage.output_tokens + usage.thinking_tokens
|
|
381
|
+
cut_off = reply.finish == "max_tokens"
|
|
382
|
+
# A schema the answer does not match is no answer: the task reads ``parsed``.
|
|
383
|
+
unparsed = response_schema is not None and reply.parsed is None
|
|
384
|
+
answered = bool(reply.text.strip()) and not cut_off and not unparsed
|
|
385
|
+
asked: Any = prompt
|
|
386
|
+
if turns:
|
|
387
|
+
asked = {"history": [turn.model_dump() for turn in turns], "prompt": prompt}
|
|
388
|
+
|
|
389
|
+
await self._audit.emit(
|
|
390
|
+
"ai_call",
|
|
391
|
+
run_id=run_id,
|
|
392
|
+
task_id=task_id,
|
|
393
|
+
step_id=step_id,
|
|
394
|
+
model=chosen,
|
|
395
|
+
input_tokens=usage.input_tokens,
|
|
396
|
+
output_tokens=output_tokens,
|
|
397
|
+
cached_tokens=usage.cached_tokens,
|
|
398
|
+
status="ok" if answered else "failed",
|
|
399
|
+
request_hash=digest(asked),
|
|
400
|
+
response_hash=digest(reply.text),
|
|
401
|
+
detail={
|
|
402
|
+
"provider": provider,
|
|
403
|
+
"temperature": temperature,
|
|
404
|
+
"schema": response_schema is not None,
|
|
405
|
+
"location": where,
|
|
406
|
+
"thinking": thinking,
|
|
407
|
+
"thinking_tokens": usage.thinking_tokens,
|
|
408
|
+
"finish_reason": reply.finish_reason,
|
|
409
|
+
"history_turns": len(turns),
|
|
410
|
+
},
|
|
411
|
+
)
|
|
412
|
+
|
|
413
|
+
# After the audit event, so a refused run still records what it used.
|
|
414
|
+
if guardrails is not None:
|
|
415
|
+
guardrails.note_tokens(usage.input_tokens + output_tokens)
|
|
416
|
+
|
|
417
|
+
if not answered:
|
|
418
|
+
raise AiNoAnswer(
|
|
419
|
+
chosen,
|
|
420
|
+
finish_reason=reply.finish_reason,
|
|
421
|
+
max_output_tokens=sent_max,
|
|
422
|
+
cut_off=cut_off,
|
|
423
|
+
unparsed=unparsed,
|
|
424
|
+
)
|
|
425
|
+
|
|
426
|
+
return AiResult(
|
|
427
|
+
text=reply.text,
|
|
428
|
+
parsed=reply.parsed,
|
|
429
|
+
conversation=[
|
|
430
|
+
*turns,
|
|
431
|
+
AiTurn(role="user", text=prompt),
|
|
432
|
+
AiTurn(role="assistant", text=reply.text),
|
|
433
|
+
],
|
|
434
|
+
model=chosen,
|
|
435
|
+
input_tokens=usage.input_tokens,
|
|
436
|
+
output_tokens=output_tokens,
|
|
437
|
+
cached_tokens=usage.cached_tokens,
|
|
438
|
+
thinking_tokens=usage.thinking_tokens,
|
|
439
|
+
)
|
|
440
|
+
|
|
441
|
+
async def decide(
|
|
442
|
+
self,
|
|
443
|
+
text: str,
|
|
444
|
+
questions: Mapping[str, Question],
|
|
445
|
+
*,
|
|
446
|
+
model: str,
|
|
447
|
+
provider: str,
|
|
448
|
+
location: str | None = None,
|
|
449
|
+
thinking: str | None = THINKING,
|
|
450
|
+
temperature: float | None = None,
|
|
451
|
+
max_output_tokens: int = 8192,
|
|
452
|
+
run_id: str | None = None,
|
|
453
|
+
task_id: str | None = None,
|
|
454
|
+
guardrails: GuardrailState | None = None,
|
|
455
|
+
) -> Decision:
|
|
456
|
+
"""Answer ``questions`` about ``text``: the Decisions API, or a prompt on any model.
|
|
457
|
+
|
|
458
|
+
A question outside the limits raises ``ValueError`` before anything is
|
|
459
|
+
sent. A decision with any question unanswered raises ``AiNoDecision``,
|
|
460
|
+
after it is audited.
|
|
461
|
+
"""
|
|
462
|
+
if provider not in AI_PROVIDERS:
|
|
463
|
+
raise ConfigurationError(
|
|
464
|
+
f"{provider!r} is not an AI provider type; ctx.decide calls "
|
|
465
|
+
f"{', '.join(AI_PROVIDERS)}"
|
|
466
|
+
)
|
|
467
|
+
reserved = sorted(Decision.RESERVED & set(questions))
|
|
468
|
+
if reserved:
|
|
469
|
+
raise ValueError(f"a question may not be named {', '.join(reserved)}")
|
|
470
|
+
thinking = level(thinking)
|
|
471
|
+
method = decision_method(provider, model)
|
|
472
|
+
version = gemini_version(model)
|
|
473
|
+
if temperature is None and version is not None and version < (3, 0):
|
|
474
|
+
temperature = 0.0
|
|
475
|
+
request = DecisionRequest(
|
|
476
|
+
model=model,
|
|
477
|
+
input=text,
|
|
478
|
+
questions=dict(questions),
|
|
479
|
+
thinking=thinking,
|
|
480
|
+
temperature=temperature,
|
|
481
|
+
max_output_tokens=max(max_output_tokens, MIN_OUTPUT_TOKENS),
|
|
482
|
+
)
|
|
483
|
+
where = self._location(provider, location)
|
|
484
|
+
api_key = await self._api_key(provider) if PROVIDER_TYPES[provider].keyed else None
|
|
485
|
+
decider: Decider
|
|
486
|
+
if method == "decisions_api":
|
|
487
|
+
assert api_key is not None
|
|
488
|
+
decider = GeminiDecisions(api_key, transport=self._http_transport)
|
|
489
|
+
else:
|
|
490
|
+
decider = PromptedDecisions(self._provider(provider, where, api_key))
|
|
491
|
+
|
|
492
|
+
reply = await decider.decide(request)
|
|
493
|
+
usage = reply.usage
|
|
494
|
+
output_tokens = usage.output_tokens + usage.thinking_tokens
|
|
495
|
+
complete = reply.complete(request)
|
|
496
|
+
await self._audit.emit(
|
|
497
|
+
"ai_call",
|
|
498
|
+
run_id=run_id,
|
|
499
|
+
task_id=task_id,
|
|
500
|
+
step_id=None,
|
|
501
|
+
model=model,
|
|
502
|
+
input_tokens=usage.input_tokens,
|
|
503
|
+
output_tokens=output_tokens,
|
|
504
|
+
cached_tokens=usage.cached_tokens,
|
|
505
|
+
status="ok" if complete else "failed",
|
|
506
|
+
request_hash=digest(_asked(text, request.questions)),
|
|
507
|
+
response_hash=digest(
|
|
508
|
+
{key: dataclasses.asdict(answer) for key, answer in reply.answers.items()}
|
|
509
|
+
),
|
|
510
|
+
detail={
|
|
511
|
+
"kind": "decision",
|
|
512
|
+
"provider": provider,
|
|
513
|
+
"location": where,
|
|
514
|
+
"method": method,
|
|
515
|
+
"calibrated": reply.calibrated,
|
|
516
|
+
"questions": len(request.questions),
|
|
517
|
+
"calls": reply.calls,
|
|
518
|
+
"temperature": temperature,
|
|
519
|
+
"thinking": thinking if method == "prompted" else None,
|
|
520
|
+
"thinking_tokens": usage.thinking_tokens,
|
|
521
|
+
"finish_reason": reply.finish_reason or reply.finish,
|
|
522
|
+
},
|
|
523
|
+
)
|
|
524
|
+
if guardrails is not None:
|
|
525
|
+
guardrails.note_tokens(usage.input_tokens + output_tokens)
|
|
526
|
+
|
|
527
|
+
if not complete:
|
|
528
|
+
raise AiNoDecision(
|
|
529
|
+
model,
|
|
530
|
+
finish=reply.finish,
|
|
531
|
+
finish_reason=reply.finish_reason,
|
|
532
|
+
missing=[key for key in request.questions if key not in reply.answers],
|
|
533
|
+
)
|
|
534
|
+
return Decision(
|
|
535
|
+
reply.answers,
|
|
536
|
+
model=model,
|
|
537
|
+
provider=provider,
|
|
538
|
+
method=method,
|
|
539
|
+
calibrated=reply.calibrated,
|
|
540
|
+
input_tokens=usage.input_tokens,
|
|
541
|
+
output_tokens=output_tokens,
|
|
542
|
+
thinking_tokens=usage.thinking_tokens,
|
|
543
|
+
)
|