Coverage for app / services / structured_generation.py: 100%

42 statements  

« prev     ^ index     » next       coverage.py v7.13.4, created at 2026-10-31 11:23 +0000

1""" 

2One-shot structured generation for the setup endpoints (agent, skill, 

3skillset, toolkit, knowledge and rules setup): one ``structured_call`` within 

4a wall-clock budget. 

5 

6``structured_call`` is the platform's one way to have a model fill a schema: 

7native constrained decoding where the model takes it, function calling 

8otherwise, salvage, and one retry that tells the model what was wrong. These 

9endpoints used their own loop until October 2026 — function calling only, 

10and a second attempt that sent the same messages again whatever had failed. 

11The provider SDK already retries transient failures (``MODEL_CALL_RETRIES``), 

12so nothing here retries an exception. 

13 

14Kept provider/schema-agnostic — callers pass their own schema and own the 

15endpoint-specific request/response shaping and validation. 

16""" 

17 

18from __future__ import annotations 

19 

20import asyncio 

21import time 

22from dataclasses import dataclass 

23from typing import Any, TypeVar 

24 

25from langchain_core.messages import BaseMessage 

26from pydantic import BaseModel 

27 

28from app.services import model_errors 

29from app.services.structured_output import structured_call 

30from app.util.logger import get_logger 

31 

32logger = get_logger(__name__) 

33 

34# Wall-clock budget for the whole generation call, its corrective retry 

35# included. Must undercut svc-core's 120s client timeout — anything slower is 

36# answering a caller that has already given up, while still holding an LLM 

37# connection. 

38GENERATION_BUDGET_S = 100.0 

39 

40SchemaT = TypeVar("SchemaT", bound=BaseModel) 

41 

42#: What the person is told when the reply could not be used. The reason 

43#: itself goes to the trace and the log, never into a response. 

44UNUSABLE_REPLY = ( 

45 "the model's reply could not be used as a configuration. Try again, or " 

46 "choose another model." 

47) 

48 

49 

50@dataclass 

51class GenerationOutcome: 

52 """What one generation produced.""" 

53 

54 config: Any | None 

55 #: Why it produced nothing, in one line, for the trace and the log. 

56 failure: str 

57 latency_ms: int 

58 #: Set when the provider refused the model outright (auth, permission, 

59 #: model not found, quota): no retry or other step can work round it. 

60 unavailable: model_errors.ModelUnavailableError | None = None 

61 

62 @property 

63 def user_message(self) -> str: 

64 """Why it failed, safe to show: never exception text.""" 

65 if self.unavailable is not None: 

66 return self.unavailable.user_message 

67 if self.failure.startswith("timeout"): 

68 return "the model took too long to answer. Try again." 

69 return UNUSABLE_REPLY 

70 

71 

72async def generate( 

73 llm: Any, 

74 schema_cls: type[SchemaT], 

75 messages: list[BaseMessage], 

76 *, 

77 purpose: str, 

78 budget_s: float = GENERATION_BUDGET_S, 

79) -> GenerationOutcome: 

80 """Have ``llm`` fill ``schema_cls`` within ``budget_s``. Never raises. 

81 

82 Usage is not counted here: the meter on every model ``build_langchain_llm`` 

83 makes records each call, and the invocation trace takes its figures. 

84 """ 

85 started = time.monotonic() 

86 

87 def elapsed() -> int: 

88 return int((time.monotonic() - started) * 1000) 

89 

90 try: 

91 result = await asyncio.wait_for( 

92 structured_call(llm, schema_cls, messages, purpose=purpose), 

93 timeout=budget_s, 

94 ) 

95 except asyncio.TimeoutError: 

96 logger.warning("[%s] generation exceeded the %.0fs budget", purpose, budget_s) 

97 return GenerationOutcome( 

98 None, f"timeout: exceeded the {budget_s:.0f}s budget", elapsed() 

99 ) 

100 except model_errors.ModelUnavailableError as exc: 

101 logger.warning("[%s] model unavailable: %s", purpose, exc) 

102 return GenerationOutcome(None, str(exc), elapsed(), unavailable=exc) 

103 if not result.ok: 

104 logger.warning("[%s] generation failed: %s", purpose, result.failure) 

105 return GenerationOutcome(result.value, result.failure, elapsed())