Coverage for app / router / app / models / transformers.py: 89%
65 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
1from uuid import UUID, uuid4
2from datetime import datetime, timedelta
3from typing import Optional, Tuple, List
4from sqlalchemy.orm import Session
6from app.db.postgres.enums import MessageEnum
7from app.db.postgres.models import Conversation, ChatMessage
8from app.router.app.models.models import PromptRequest
9from app.services import attachments as attachments_service
10from app.services import rule_engine
11from app.services.ai_client import invoke_model, AIServiceError, ModelRefusedError
12from app.services.turns import RunningTurn, TurnStopped
13from app.util import history_window
14import logging
16logger = logging.getLogger(__name__)
19# def get_model_callable(model: Model) -> Optional[callable]:
20# if not model.callable_path:
21# return None
23# return resolve_callable(model.callable_path)
26def build_system_messages(
27 system_messages: list[str],
28 sent_at: datetime,
29 offset: int = 0,
30) -> List[ChatMessage]:
31 """
32 Build ChatMessage ORM objects for system messages.
34 ``offset`` is the number of microseconds to add to ``sent_at`` for the
35 first message in this batch; subsequent messages increment by one more
36 microsecond each. This guarantees deterministic DB ordering when all
37 messages in a request share the same base timestamp.
38 """
39 messages = []
40 for i, msg in enumerate(system_messages):
41 messages.append(
42 ChatMessage(
43 id=uuid4(),
44 role=MessageEnum.Role.SYSTEM,
45 status=MessageEnum.Status.COMPLETED,
46 content=msg,
47 token_count=len(msg.split()),
48 sent_at=sent_at + timedelta(microseconds=offset + i),
49 )
50 )
51 return messages
54def build_prompt_messages(
55 *,
56 prompt: str,
57 response: str,
58 sent_at: datetime,
59 offset: int = 0,
60 output_tokens: int = 0,
61 temperature: float | None = None,
62 output_format: str | None = None,
63 output_schema: str | None = None,
64 trace: list[dict] | None = None,
65 status: MessageEnum.Status = MessageEnum.Status.COMPLETED,
66 rule_name: str | None = None,
67 stopped: bool = False,
68 invocation_id: str | UUID | None = None,
69 withheld: dict | None = None,
70 user_meta: dict | None = None,
71) -> List[ChatMessage]:
72 """
73 Build ChatMessage objects for user prompt and model assistant response.
75 ``offset`` controls the microsecond offset from ``sent_at`` for the user
76 message; the assistant message gets ``offset + 1``. Callers that prepend
77 system/file messages must pass the correct offset so the user message always
78 sorts after those messages and the assistant always sorts after the user.
80 The assistant message carries a ``meta`` JSON blob with request parameters
81 and token counts so they can be surfaced in the UI when conversation history
82 is reloaded.
84 ``status`` records the outcome of this turn (see ``ChatMessage.status``);
85 the user's message always stays COMPLETED, only the assistant message
86 reflects a block/error so the turn is still visible in History/Activity.
88 ``invocation_id`` is the turn's id, on both messages: the key of the
89 answer's decision record (see ``ChatMessage.invocation_id``).
91 ``withheld`` marks an answer an Output rule withheld (``meta.withheld``):
92 ``response`` is then the rule's message.
94 ``user_meta`` goes on the user's message: the documents it attached
95 (``attachments.message_meta``).
96 """
97 turn_invocation = UUID(str(invocation_id)) if invocation_id else None
98 user_msg = ChatMessage(
99 id=uuid4(),
100 role=MessageEnum.Role.USER,
101 status=MessageEnum.Status.COMPLETED,
102 content=prompt,
103 token_count=len(prompt.split()),
104 sent_at=sent_at + timedelta(microseconds=offset),
105 meta=user_meta or None,
106 invocation_id=turn_invocation,
107 )
109 assistant_meta: dict = {}
110 if output_tokens > 0:
111 assistant_meta["token_count"] = output_tokens
112 if temperature is not None:
113 assistant_meta["temperature"] = temperature
114 if output_format and output_format != "markdown":
115 assistant_meta["output_format"] = output_format
116 if output_schema:
117 assistant_meta["output_schema"] = output_schema
118 if rule_name:
119 assistant_meta["rule"] = rule_name
120 if stopped:
121 # The person stopped it: ``response`` is what it had written.
122 assistant_meta["stopped"] = True
123 if withheld:
124 assistant_meta["withheld"] = withheld
126 assistant_msg = ChatMessage(
127 id=uuid4(),
128 role=MessageEnum.Role.ASSISTANT,
129 status=status,
130 content=response,
131 token_count=output_tokens or len(response.split()),
132 sent_at=sent_at + timedelta(microseconds=offset + 1),
133 meta=assistant_meta or None,
134 trace=trace,
135 invocation_id=turn_invocation,
136 )
138 return [user_msg, assistant_msg]
141def prompt_model(
142 *,
143 db: Session,
144 provider: str,
145 model_name: str,
146 config: dict,
147 request: PromptRequest,
148 extrahist: list[ChatMessage],
149 conversation_id: str | None = None,
150 redaction: rule_engine.RulePass | None = None,
151 stoppable: RunningTurn | None = None,
152 attachments: list[dict] | None = None,
153) -> Tuple[Optional[str], list, Optional[Conversation], Tuple[int, int], list]:
154 """Return (response, history, conversation, (input_tokens,
155 output_tokens), rule_events).
157 ``rule_events`` are the governance actions svc-ai enforced on this call.
159 ``attachments`` are the conversation's documents as svc-ai takes them
160 (``attachments.wire``), through the policy rules already: sent beside
161 the words, never pasted into them, so the stored message is the words
162 and a later turn is sent the documents again from the library.
164 On an ``AIServiceError`` from svc-ai, ``response`` is ``None`` but the rest
165 of the tuple is still populated (rather than returning bare ``None``) so
166 the caller can still persist the attempted turn as an errored message
167 instead of losing it.
169 ``redaction`` is the policy pass the prompt went through. The history
170 reaches the model beside the prompt, so it meets the same PII redaction.
172 ``stoppable`` is the chat turn this call belongs to: its Stop ends the
173 call (``ai_client.invoke_model``), raising ``TurnStopped``.
174 """
175 conversation = None
176 history = []
178 if request.conversation_id:
179 conversation = db.get(Conversation, request.conversation_id)
180 if conversation:
181 history = conversation.messages
183 # The newest messages within the outer bound (``history_window``), every
184 # system message kept: a direct chat sends what it holds to the model, and
185 # a long one used to send all of it on every turn.
186 fmt_hist = [
187 _history_entry(msg)
188 for msg in history_window.newest(
189 list(history) + list(extrahist),
190 role=lambda m: str(m.role.value),
191 content=lambda m: m.content,
192 )
193 ]
194 if redaction is not None:
195 fmt_hist = redaction.redact_history(fmt_hist)
197 # Sizes, never the text: a prompt in the logs outlives every rule that
198 # redacted it everywhere else.
199 logger.info(
200 "Prompting model %s (%d prompt characters, %d history messages)",
201 model_name,
202 len(request.prompt or ""),
203 len(fmt_hist),
204 )
206 if request.temperature is not None:
207 config = {**config, "temperature": request.temperature}
209 try:
210 response, input_tokens, output_tokens, remote_rule_events = invoke_model(
211 provider=provider,
212 model_name=model_name,
213 config=config,
214 prompt=request.prompt,
215 messages=fmt_hist,
216 output_format=request.output_format,
217 output_schema=request.output_schema,
218 conversation_id=conversation_id,
219 stoppable=stoppable,
220 attachments=attachments,
221 )
222 except (TurnStopped, ModelRefusedError):
223 # Stop, or something a person must fix said by svc-ai in words safe
224 # to show: the route records the turn either way.
225 raise
226 except AIServiceError:
227 logger.exception("svc-ai invocation failed")
228 return (None, history, conversation, (0, 0), [])
230 return (
231 response,
232 history,
233 conversation,
234 (input_tokens, output_tokens),
235 remote_rule_events,
236 )
239def _history_entry(msg: ChatMessage) -> dict:
240 """A stored message as svc-ai is sent it: a user message names the
241 documents it attached (``attachments``), which svc-ai sends again beside
242 the turn."""
243 entry: dict = {"role": str(msg.role.value), "content": msg.content}
244 if msg.role == MessageEnum.Role.USER and (
245 refs := attachments_service.stored_refs(getattr(msg, "meta", None))
246 ):
247 entry["attachments"] = [str(ref["name"]) for ref in refs]
248 return entry