Coverage for app / router / app / models / router.py: 95%
156 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
1import logging
2from time import perf_counter
3from uuid import UUID, uuid4
5from fastapi import APIRouter, Depends, HTTPException, status
6from sqlalchemy.orm import Session
8import app.router.app.conversations.transformers as conversation_transformers
9import app.router.app.models.transformers as model_transformers
10from app.db.postgres.crud_schemas import Schema
11from app.db.postgres.enums import MessageEnum, UsageEnum
12from app.db.postgres.models import Conversation, User
13from app.dependency.base import get_db
14from app.dependency.resource_access import verify_conversation_access
15from app.dependency.user.context import get_current_user
16from app.router.app.models.models import PromptRequest, PromptResponse
17from app.services import ai_client
18from app.services import attachments as attachments_service
19from app.services import governance_activity as activity_service
20from app.services import review as review_service
21from app.services import rule_engine
22from app.services import spend_limits
23from app.services import turns, uploads
24from app.services import usage as usage_service
25from app.services import withholding
26from app.services.ai_client import (
27 AIServiceError,
28 ModelNotAvailableError,
29 get_model,
30 list_models,
31 list_providers,
32)
33from app.util.time import aware_utcnow
35logger = logging.getLogger(__name__)
37model_router = APIRouter(prefix="/models", tags=["App - Models"])
40@model_router.get("/providers")
41def get_providers():
42 """List all LLM providers registered in svc-ai."""
43 try:
44 return list_providers()
45 except AIServiceError as exc:
46 raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail=str(exc))
49@model_router.get("")
50def get_models(
51 provider_id: UUID | None = None,
52 is_available: bool | None = None,
53 include_archived: bool = False,
54 current_user: User = Depends(get_current_user),
55):
56 """List all models from svc-ai's canonical registry.
58 ``include_archived`` adds the models taken out of it, so a page can name
59 the model an old conversation or trace ran on.
60 """
61 try:
62 return list_models(
63 provider_id=provider_id,
64 is_available=is_available,
65 include_archived=include_archived,
66 )
67 except AIServiceError as exc:
68 raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail=str(exc))
71@model_router.get("/{model_id}", response_model=Schema.Model.ReadWithProvider)
72def get_model_by_id(model_id: UUID):
73 """Fetch a single model by its svc-ai UUID."""
74 try:
75 return get_model(model_id)
76 except ModelNotAvailableError as exc:
77 raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc))
78 except AIServiceError as exc:
79 raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail=str(exc))
82@model_router.post("/{model_id}/prompt", response_model=PromptResponse)
83def model_prompt(
84 model_id: UUID,
85 prompt_request: PromptRequest,
86 db: Session = Depends(get_db),
87 current_user: User = Depends(get_current_user),
88):
89 """
90 Prompt a model directly. model_id is the svc-ai llm_models UUID.
91 Conversation history is persisted locally in svc-core.
93 A plain ``def``: it runs in a worker thread, which a client that goes
94 away cannot cancel, so the answer is stored either way. The turn is in
95 the registry of running turns while it runs (``app/services/turns.py``):
96 a page that comes back sees it, and ``POST /app/turns/{id}/stop`` — by
97 the request's ``turn_id`` — ends it, keeping what it had written.
98 """
99 verify_conversation_access(prompt_request.conversation_id, current_user, db)
100 # Chosen now, not when the turn is stored: svc-ai records it on the
101 # turn's trace, the registry shows the turn under it, and a refused or
102 # failed turn below has somewhere to be stored.
103 conversation_id = prompt_request.conversation_id or uuid4()
104 try:
105 turn = turns.registry.start(
106 kind="model",
107 user_id=str(current_user.id),
108 target_id=str(model_id),
109 conversation_id=str(conversation_id),
110 turn_id=prompt_request.turn_id,
111 )
112 except turns.TurnConflict as exc:
113 raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(exc))
114 except ValueError:
115 raise HTTPException(
116 status_code=status.HTTP_409_CONFLICT, detail="That turn id is in use."
117 )
118 # The turn's id: both rule phases, the ledger row, the messages, any
119 # flags and svc-ai's traces carry it (the answer's decision record).
120 invocation_id = rule_engine.new_invocation_id()
121 try:
122 with ai_client.in_invocation(invocation_id):
123 return _model_turn(
124 model_id, prompt_request, db, current_user, turn, invocation_id
125 )
126 finally:
127 # Only now, with the turn stored: a page that sees it gone reads the
128 # conversation and finds the answer there.
129 turns.registry.finish(turn)
132def _model_turn(
133 model_id: UUID,
134 prompt_request: PromptRequest,
135 db: Session,
136 current_user: User,
137 turn: turns.RunningTurn,
138 invocation_id: str,
139) -> PromptResponse:
140 """One direct model turn, from its rules to the stored answer."""
141 from app.dependency.workspace import request_workspace
143 sent_at = aware_utcnow()
144 # The workspace the chat happens in (``?workspace=``): its rules govern
145 # the turn, its ledger counts it and its conversation list shows it — an
146 # organisation's budget sees model chat done in the organisation, which
147 # used to land in the person's Personal workspace whatever page they
148 # were on.
149 ws = request_workspace(db, current_user)
151 try:
152 model_info = get_model(model_id)
153 except ModelNotAvailableError as exc:
154 raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc))
155 except AIServiceError as exc:
156 raise HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail=str(exc))
158 provider = model_info["provider"]["name"]
159 model_name = model_info["model_name"]
160 config = model_info.get("config") or {}
162 # The documents this message attaches, from the request workspace's
163 # library only: beside the words, never pasted into them, as agent chat
164 # sends them (``app/services/attachments.py``).
165 try:
166 this_turn = attachments_service.turn_attachments(
167 db, prompt_request.file_ids, ws
168 )
169 except uploads.DocumentsNotReady as exc:
170 raise HTTPException(
171 status_code=status.HTTP_409_CONFLICT, detail=exc.message
172 ) from None
173 except attachments_service.TooManyDocuments as exc:
174 raise HTTPException(
175 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=exc.message
176 ) from None
177 if not prompt_request.prompt.strip() and not this_turn:
178 raise HTTPException(
179 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
180 detail="No prompt provided",
181 )
182 merged_request = prompt_request
184 # Chosen by the route (``model_prompt``) so svc-ai records the correct
185 # conversation_id even for the very first message of a new conversation,
186 # and so a blocked/failed turn below has somewhere to be persisted.
187 target_conversation_id = turn.conversation_id
188 existing_conversation = (
189 db.get(Conversation, merged_request.conversation_id)
190 if merged_request.conversation_id
191 else None
192 )
193 # What the turn carries: this message's documents, then those the
194 # conversation's earlier messages attached.
195 turn_docs = attachments_service.for_turn(
196 this_turn,
197 attachments_service.earlier_attachments(
198 db, existing_conversation, ws, exclude=[d.id for d in this_turn]
199 ),
200 )
201 # What the user's message keeps beside its words: its documents, by id.
202 user_meta = attachments_service.message_meta(None, this_turn)
204 def _persist_failed_prompt(
205 message: str,
206 turn_status: MessageEnum.Status,
207 rule_name: str | None = None,
208 trace: list[dict] | None = None,
209 prompt: str | None = None,
210 stopped: bool = False,
211 ) -> None:
212 """Persist a turn that never reached (or never returned from) svc-ai
213 so it's still visible in History/Activity instead of being lost."""
214 failed_messages = model_transformers.build_prompt_messages(
215 prompt=prompt if prompt is not None else merged_request.prompt,
216 response=message,
217 sent_at=sent_at,
218 status=turn_status,
219 rule_name=rule_name,
220 trace=trace,
221 stopped=stopped,
222 invocation_id=invocation_id,
223 user_meta=user_meta,
224 )
225 if existing_conversation:
226 conversation_transformers.update_conversation(
227 db=db,
228 conversation=existing_conversation,
229 messages=failed_messages,
230 input_tokens=0,
231 output_tokens=0,
232 )
233 else:
234 conversation_transformers.create_conversation(
235 db=db,
236 owner_user_id=current_user.id,
237 ai_model_id=model_id,
238 messages=failed_messages,
239 input_tokens=0,
240 output_tokens=0,
241 conversation_id=UUID(target_conversation_id),
242 workspace=ws,
243 )
245 # ── Rule enforcement: policy (input) ─────────────────────────────────────
246 # One id for both phases (``invocation_id``), so the policy rules that ran
247 # on this prompt and the audit rules that ran on its answer are one group
248 # in the activity log rather than two unrelated lists.
249 # The rules read this message's documents with its words, as agent
250 # chat's do (``attachments.governed_text``); what they redact is then
251 # redacted in the words and in every document.
252 governed_prompt = attachments_service.governed_text(
253 merged_request.prompt, this_turn
254 )
255 input_ctx = {
256 "prompt": governed_prompt,
257 "execution_type": "model",
258 "model_id": str(model_id),
259 "model_name": model_name,
260 "provider": provider,
261 "scope_type": "model",
262 "scope_id": str(model_id),
263 rule_engine.INVOCATION_CONTEXT_KEY: invocation_id,
264 rule_engine.WORKSPACE_CONTEXT_KEY: ws.key,
265 }
266 try:
267 input_rules = rule_engine.evaluate_input(
268 db, governed_prompt, input_ctx, str(current_user.id)
269 )
270 filtered_prompt, _ = input_rules
271 except rule_engine.RuleBlock as exc:
272 _persist_failed_prompt(
273 exc.message,
274 MessageEnum.Status.BLOCKED,
275 rule_name=exc.rule_name,
276 trace=rule_engine.build_block_trace_from_exc(exc),
277 )
278 raise HTTPException(
279 status_code=status.HTTP_403_FORBIDDEN,
280 detail={"rule": exc.rule_name, "message": exc.message},
281 )
282 if this_turn:
283 filtered_prompt = input_rules.redact(merged_request.prompt)
284 if filtered_prompt != merged_request.prompt:
285 merged_request = merged_request.model_copy(update={"prompt": filtered_prompt})
286 turn_docs = attachments_service.redacted(turn_docs, input_rules)
287 user_meta = attachments_service.message_meta(None, turn_docs)
288 # What a page that comes back shows while the answer is written: the
289 # message as it will be stored.
290 turn.prompt = merged_request.prompt
291 turn.meta = user_meta
293 sys_msgs = model_transformers.build_system_messages(
294 merged_request.system_messages,
295 sent_at,
296 )
298 # Timed around the svc-ai call for the ledger's latency figure. Wall
299 # clock on purpose: what matters is how long the caller waited, not how
300 # much of that was the provider.
301 invocation_started = perf_counter()
302 refusal: ai_client.ModelRefusedError | None = None
303 stopped: turns.TurnStopped | None = None
304 # svc-ai stops the call at what is left of the tightest budget governing
305 # it (``app/services/spend_limits.py``), and its web tools — a model may
306 # be given some — hold to the sources the Tools rules set.
307 with (
308 ai_client.usage_capture() as used,
309 ai_client.in_turn_governance(input_rules),
310 ):
311 try:
312 prompt_result = model_transformers.prompt_model(
313 db=db,
314 provider=provider,
315 model_name=model_name,
316 config=config,
317 request=merged_request,
318 extrahist=sys_msgs,
319 conversation_id=target_conversation_id,
320 redaction=input_rules,
321 stoppable=turn,
322 attachments=attachments_service.wire(turn_docs),
323 )
324 except ai_client.ModelRefusedError as exc:
325 # No route on this deployment's backend, model access,
326 # credentials, quota or the spending ceiling: svc-ai says what to
327 # fix, and the turn and the response say it too.
328 refusal = exc
329 except turns.TurnStopped as exc:
330 stopped = exc
332 invocation_latency_ms = (perf_counter() - invocation_started) * 1000
334 if stopped is not None:
335 # The person pressed Stop: svc-ai's run ended with the stream, and
336 # the turn is stored with what it had written — what the chat shows.
337 # A failed attempt on the ledger, as the agent chat's Stop records,
338 # with what the call had cost: Stop cancelled the stream before its
339 # terminal frame, so that is read from svc-ai's trace of the turn.
340 usage_service.record_usage(
341 db,
342 owner_user_id=str(current_user.id),
343 execution_type="model",
344 scope_type="model",
345 scope_id=str(model_id),
346 ai_model_id=str(model_info.get("id") or model_id),
347 model_info=model_info,
348 latency_ms=invocation_latency_ms,
349 outcome=UsageEnum.Outcome.error,
350 source_type=UsageEnum.Source.model,
351 source_id=model_id,
352 measured=ai_client.reconcile_turn_usage(
353 used, invocation_id, current_user.id, legs=1
354 ),
355 workspace=ws,
356 invocation_id=invocation_id,
357 )
358 # What it had written, unless a withhold rule governs it: then none
359 # of it was checked, and a neutral line is kept instead.
360 written = (
361 withholding.HELD_TEXT
362 if rule_engine.may_withhold(db, input_ctx, str(current_user.id))
363 else stopped.partial.strip() or turns.STOPPED_TEXT
364 )
365 _persist_failed_prompt(written, MessageEnum.Status.ERROR, stopped=True)
366 return PromptResponse(
367 response=written,
368 conversation_id=UUID(target_conversation_id),
369 stopped=True,
370 invocation_id=invocation_id,
371 **usage_service.turn_cost_fields(db, invocation_id),
372 )
374 if refusal is not None:
375 response = None
376 else:
377 (
378 response,
379 history,
380 conversation,
381 (input_tokens, output_tokens),
382 remote_rule_events,
383 ) = prompt_result
385 if response is None:
386 # On the ledger as a failed attempt, so an error rate per model is a
387 # figure that exists, with what the attempt cost. A refusal's error
388 # frame says what the run spent before it failed; a failure on this
389 # side of the stream may have cut it off mid-call, so svc-ai's trace
390 # of the turn is read for that.
391 usage_service.record_usage(
392 db,
393 owner_user_id=str(current_user.id),
394 execution_type="model",
395 scope_type="model",
396 scope_id=str(model_id),
397 ai_model_id=str(model_info.get("id") or model_id),
398 model_info=model_info,
399 latency_ms=invocation_latency_ms,
400 outcome=UsageEnum.Outcome.error,
401 source_type=UsageEnum.Source.model,
402 source_id=model_id,
403 measured=(
404 used
405 if refusal is not None
406 else ai_client.reconcile_turn_usage(
407 used, invocation_id, current_user.id, legs=1
408 )
409 ),
410 workspace=ws,
411 invocation_id=invocation_id,
412 )
413 message = refusal.user_message if refusal else "Model unavailable."
414 if refusal is not None:
415 # A budget stopped it part-way: on the record beside the row
416 # that let it start.
417 spend_limits.record_stop(refusal, input_ctx, str(current_user.id), db=db)
418 _persist_failed_prompt(message, MessageEnum.Status.ERROR)
419 raise HTTPException(
420 status_code=(
421 status.HTTP_502_BAD_GATEWAY
422 if refusal
423 else status.HTTP_503_SERVICE_UNAVAILABLE
424 ),
425 detail=message,
426 )
428 # ── Rule enforcement: audit (output) ─────────────────────────────────────
429 output_ctx = {
430 **input_ctx,
431 "response": response,
432 # The ledger's figures for this call, so an audit rule on latency or
433 # cost has a value to compare.
434 **usage_service.audit_figures(
435 latency_ms=invocation_latency_ms,
436 measured=used,
437 input_tokens=input_tokens,
438 output_tokens=output_tokens,
439 model_info=model_info,
440 ),
441 }
442 output_rules = rule_engine.evaluate_output(
443 db, response, output_ctx, str(current_user.id)
444 )
445 response, output_rule_events = output_rules
446 withheld = getattr(output_rules, "withheld", None)
448 # Every applicable rule as trace frames — one node per phase, with svc-ai's
449 # enforcement of the same rules merged into each — so governance is
450 # visible in the chat trace and on the Activity page.
451 rule_trace = rule_engine.build_turn_rule_trace(
452 input_rules, output_rules, remote_rule_events
453 )
455 effective_temperature = (
456 merged_request.temperature
457 if merged_request.temperature is not None
458 else config.get("temperature", 0.7)
459 )
460 # ── Governance usage ledger ──────────────────────────────────────────────
461 # Recorded after the call succeeded and before the turn is committed, so
462 # the counter behind rate limits and cost caps can never include a turn
463 # that was rolled back. Cost is what svc-ai measured for the call
464 # (``used``); the model record fetched above prices it when svc-ai did not.
465 usage_service.record_usage(
466 db,
467 owner_user_id=str(current_user.id),
468 execution_type="model",
469 scope_type="model",
470 scope_id=str(model_id),
471 # The model that ran: what a per-model quota counts
472 # (``ModelScope.usage_filter``) and the stats' "model prompted
473 # directly" dimension reads.
474 ai_model_id=str(model_info.get("id") or model_id),
475 input_tokens=input_tokens,
476 output_tokens=output_tokens,
477 model_info=model_info,
478 latency_ms=invocation_latency_ms,
479 source_type=UsageEnum.Source.model,
480 source_id=model_id,
481 measured=used,
482 workspace=ws,
483 invocation_id=invocation_id,
484 )
486 # The user message is the words, its documents named beside them
487 # (``meta.attachments``): a later turn is sent them again from the
488 # library, so they are no longer pasted into the stored text.
489 #
490 # Each message in the same turn must have a strictly increasing sent_at so
491 # the DB ORDER BY sent_at query returns them in the right order (system
492 # messages before user, user before assistant). Without this, PostgreSQL
493 # may return same-timestamp rows in any order, breaking conversation
494 # structure and silently losing file context for subsequent turns.
495 #
496 # A system prompt is stored once, not with every turn that sends it: the
497 # chat page sends its system prompt on every turn, and storing each copy
498 # had turn N send it N times.
499 stored_system = {
500 message.content
501 for message in (conversation.messages if conversation else [])
502 if message.role == MessageEnum.Role.SYSTEM
503 }
504 new_system = [
505 content
506 for content in dict.fromkeys(merged_request.system_messages)
507 if content not in stored_system
508 ]
509 new_messages = model_transformers.build_system_messages(
510 new_system,
511 sent_at,
512 offset=0,
513 ) + model_transformers.build_prompt_messages(
514 prompt=merged_request.prompt,
515 response=response,
516 sent_at=sent_at,
517 offset=len(new_system),
518 output_tokens=output_tokens,
519 temperature=effective_temperature,
520 output_format=merged_request.output_format,
521 output_schema=merged_request.output_schema,
522 trace=rule_trace or None,
523 invocation_id=invocation_id,
524 withheld=withheld.meta() if withheld is not None else None,
525 user_meta=user_meta,
526 )
528 if conversation:
529 if conversation.ai_model_id != model_id:
530 raise HTTPException(
531 status_code=status.HTTP_409_CONFLICT,
532 detail="Conversation belongs to a different model.",
533 )
534 conversation_transformers.update_conversation(
535 db=db,
536 conversation=conversation,
537 messages=new_messages,
538 input_tokens=input_tokens,
539 output_tokens=output_tokens,
540 )
541 else:
542 conversation = conversation_transformers.create_conversation(
543 db=db,
544 owner_user_id=current_user.id,
545 ai_model_id=model_id,
546 messages=new_messages,
547 input_tokens=input_tokens,
548 output_tokens=output_tokens,
549 conversation_id=UUID(target_conversation_id),
550 workspace=ws,
551 )
553 # Recorded after persistence so the flag points at a conversation that
554 # exists. Flags svc-ai raised arrive on `remote_rule_events` and land in
555 # the same queue as the ones enforced here.
556 review_service.record_flags(
557 db,
558 [*(remote_rule_events or []), *output_rule_events],
559 owner_user_id=str(current_user.id),
560 response=response,
561 execution_type="model",
562 conversation_id=conversation.id,
563 ai_model_id=str(model_info.get("id") or model_id),
564 workspace=ws,
565 invocation_id=invocation_id,
566 )
567 # The answer a withhold rule held, kept for review — not on the
568 # conversation, which stores the rule's message.
569 review_service.record_withheld(
570 db,
571 withheld,
572 owner_user_id=str(current_user.id),
573 execution_type="model",
574 conversation_id=conversation.id,
575 ai_model_id=str(model_info.get("id") or model_id),
576 workspace=ws,
577 invocation_id=invocation_id,
578 )
579 # …and point this prompt's governance evaluations at the message they ran
580 # on, which is the first moment either id exists.
581 activity_service.link_invocation(
582 db,
583 invocation_id,
584 conversation_id=conversation.id,
585 # The assistant message this turn just wrote — taken from the rows
586 # built above rather than re-read, so it is the right one even in a
587 # conversation that already had a dozen.
588 message_id=next(
589 (
590 message.id
591 for message in reversed(new_messages)
592 if message.role == MessageEnum.Role.ASSISTANT
593 ),
594 None,
595 ),
596 )
597 db.commit()
599 return PromptResponse(
600 response=response,
601 conversation_id=conversation.id,
602 output_tokens=output_tokens,
603 trace=rule_trace or None,
604 invocation_id=invocation_id,
605 withheld=withheld.meta() if withheld is not None else None,
606 **usage_service.turn_cost_fields(db, invocation_id),
607 )