|
| 1 | +"""Minimal LiteLLM response_format selection from authoritative state. |
| 2 | +
|
| 3 | +Flow: |
| 4 | +Context Compiler state -> host response_format decision -> LiteLLM model call. |
| 5 | +
|
| 6 | +This example keeps model execution optional so tests can validate behavior |
| 7 | +without a live provider. |
| 8 | +""" |
| 9 | + |
| 10 | +import os |
| 11 | +from collections.abc import Callable, Mapping |
| 12 | +from importlib import import_module |
| 13 | +from typing import Any, TypedDict, cast |
| 14 | + |
| 15 | +from context_compiler import ( |
| 16 | + POLICY_PROHIBIT, |
| 17 | + POLICY_USE, |
| 18 | + State, |
| 19 | + create_engine, |
| 20 | + get_clarify_prompt, |
| 21 | + get_decision_state, |
| 22 | + get_policy_items, |
| 23 | + is_clarify, |
| 24 | +) |
| 25 | +from context_compiler.engine import Engine |
| 26 | + |
| 27 | +try: |
| 28 | + from host_support import print_startup_config, resolve_provider_config |
| 29 | +except ImportError: |
| 30 | + from host_support.provider_mode import print_startup_config, resolve_provider_config |
| 31 | + |
| 32 | +COMPACT_SUMMARY_RESPONSE_FORMAT: dict[str, Any] = { |
| 33 | + "type": "json_schema", |
| 34 | + "json_schema": { |
| 35 | + "name": "compact_summary", |
| 36 | + "schema": { |
| 37 | + "type": "object", |
| 38 | + "properties": { |
| 39 | + "summary": { |
| 40 | + "type": "string", |
| 41 | + "description": "A compact summary of the answer.", |
| 42 | + } |
| 43 | + }, |
| 44 | + "required": ["summary"], |
| 45 | + "additionalProperties": False, |
| 46 | + }, |
| 47 | + }, |
| 48 | +} |
| 49 | + |
| 50 | +ACTION_PLAN_RESPONSE_FORMAT: dict[str, Any] = { |
| 51 | + "type": "json_schema", |
| 52 | + "json_schema": { |
| 53 | + "name": "action_plan", |
| 54 | + "schema": { |
| 55 | + "type": "object", |
| 56 | + "properties": { |
| 57 | + "steps": { |
| 58 | + "type": "array", |
| 59 | + "items": {"type": "string"}, |
| 60 | + "description": "Ordered next steps for the user.", |
| 61 | + } |
| 62 | + }, |
| 63 | + "required": ["steps"], |
| 64 | + "additionalProperties": False, |
| 65 | + }, |
| 66 | + }, |
| 67 | +} |
| 68 | + |
| 69 | +_RESPONSE_FORMAT_BY_ITEM: dict[str, dict[str, Any]] = { |
| 70 | + "compact_summary": COMPACT_SUMMARY_RESPONSE_FORMAT, |
| 71 | + "action_plan": ACTION_PLAN_RESPONSE_FORMAT, |
| 72 | +} |
| 73 | + |
| 74 | + |
| 75 | +class TurnPlan(TypedDict): |
| 76 | + decision_kind: str |
| 77 | + clarify_prompt: str | None |
| 78 | + selected_response_format_item: str | None |
| 79 | + response_format: dict[str, Any] | None |
| 80 | + |
| 81 | + |
| 82 | +class _LiteLLMCallKwargs(TypedDict, total=False): |
| 83 | + model: str |
| 84 | + messages: list[dict[str, str]] |
| 85 | + temperature: float |
| 86 | + api_base: str |
| 87 | + api_key: str |
| 88 | + response_format: dict[str, Any] |
| 89 | + |
| 90 | + |
| 91 | +def select_litellm_response_format(state: State) -> tuple[str | None, dict[str, Any] | None]: |
| 92 | + """Return (policy_item, response_format) or (None, None) when no safe match exists.""" |
| 93 | + |
| 94 | + use_items = set(get_policy_items(state, POLICY_USE)) |
| 95 | + prohibit_items = set(get_policy_items(state, POLICY_PROHIBIT)) |
| 96 | + |
| 97 | + for item, response_format in _RESPONSE_FORMAT_BY_ITEM.items(): |
| 98 | + if item in use_items and item not in prohibit_items: |
| 99 | + return item, response_format |
| 100 | + |
| 101 | + return None, None |
| 102 | + |
| 103 | + |
| 104 | +def plan_turn(user_input: str, engine: Engine) -> TurnPlan: |
| 105 | + """Run compiler step and decide whether to request LiteLLM structured output.""" |
| 106 | + |
| 107 | + decision = engine.step(user_input) |
| 108 | + if is_clarify(decision): |
| 109 | + return { |
| 110 | + "decision_kind": "clarify", |
| 111 | + "clarify_prompt": get_clarify_prompt(decision), |
| 112 | + "selected_response_format_item": None, |
| 113 | + "response_format": None, |
| 114 | + } |
| 115 | + |
| 116 | + decision_state = get_decision_state(decision) |
| 117 | + compiled_state = decision_state if decision_state is not None else engine.state |
| 118 | + selected_item, response_format = select_litellm_response_format(compiled_state) |
| 119 | + |
| 120 | + return { |
| 121 | + "decision_kind": str(decision["kind"]), |
| 122 | + "clarify_prompt": None, |
| 123 | + "selected_response_format_item": selected_item, |
| 124 | + "response_format": response_format, |
| 125 | + } |
| 126 | + |
| 127 | + |
| 128 | +def _get_litellm_completion() -> Callable[..., object]: |
| 129 | + litellm_module = import_module("litellm") |
| 130 | + return cast(Callable[..., object], litellm_module.completion) |
| 131 | + |
| 132 | + |
| 133 | +def _extract_response_content(response: object) -> str | None: |
| 134 | + if isinstance(response, Mapping): |
| 135 | + choices = response.get("choices") |
| 136 | + if isinstance(choices, list) and choices: |
| 137 | + first = choices[0] |
| 138 | + if isinstance(first, Mapping): |
| 139 | + message = first.get("message") |
| 140 | + if isinstance(message, Mapping): |
| 141 | + content = message.get("content") |
| 142 | + if isinstance(content, str): |
| 143 | + return content |
| 144 | + |
| 145 | + choices_attr = getattr(response, "choices", None) |
| 146 | + if isinstance(choices_attr, list) and choices_attr: |
| 147 | + first = choices_attr[0] |
| 148 | + message_attr = getattr(first, "message", None) |
| 149 | + content_attr = getattr(message_attr, "content", None) |
| 150 | + if isinstance(content_attr, str): |
| 151 | + return content_attr |
| 152 | + |
| 153 | + return None |
| 154 | + |
| 155 | + |
| 156 | +def optional_litellm_call( |
| 157 | + *, |
| 158 | + user_input: str, |
| 159 | + response_format: Mapping[str, Any] | None, |
| 160 | +) -> str: |
| 161 | + """Optional smoke call to LiteLLM. |
| 162 | +
|
| 163 | + If `response_format` is provided, it is passed through unchanged. |
| 164 | + """ |
| 165 | + |
| 166 | + try: |
| 167 | + completion = _get_litellm_completion() |
| 168 | + except ModuleNotFoundError as exc: |
| 169 | + raise RuntimeError("litellm is required. Install with: pip install litellm") from exc |
| 170 | + |
| 171 | + config = resolve_provider_config(default_model="openai/gpt-4o-mini") |
| 172 | + print_startup_config(config) |
| 173 | + |
| 174 | + kwargs: _LiteLLMCallKwargs = { |
| 175 | + "model": config.model, |
| 176 | + "messages": [{"role": "user", "content": user_input}], |
| 177 | + "temperature": 0, |
| 178 | + "api_base": config.base_url, |
| 179 | + } |
| 180 | + if config.api_key: |
| 181 | + kwargs["api_key"] = config.api_key |
| 182 | + if response_format is not None: |
| 183 | + kwargs["response_format"] = dict(response_format) |
| 184 | + |
| 185 | + response = completion(**kwargs) |
| 186 | + content = _extract_response_content(response) |
| 187 | + if content is None: |
| 188 | + raise RuntimeError("LiteLLM response missing choices[0].message.content") |
| 189 | + return content |
| 190 | + |
| 191 | + |
| 192 | +def main() -> None: |
| 193 | + engine = create_engine() |
| 194 | + |
| 195 | + # Demonstration setup. |
| 196 | + engine.step("use compact_summary") |
| 197 | + engine.step("prohibit action_plan") |
| 198 | + |
| 199 | + plan = plan_turn("Summarize what changed in this project.", engine) |
| 200 | + print("decision_kind:", plan["decision_kind"]) |
| 201 | + print("selected_response_format_item:", plan["selected_response_format_item"]) |
| 202 | + print("response_format_selected:", plan["response_format"] is not None) |
| 203 | + |
| 204 | + # Optional model execution path; disabled by default. |
| 205 | + if os.getenv("RUN_LITELLM_SMOKE") == "1": |
| 206 | + response = optional_litellm_call( |
| 207 | + user_input="Summarize what changed in this project.", |
| 208 | + response_format=plan["response_format"], |
| 209 | + ) |
| 210 | + print("litellm_response:", response) |
| 211 | + |
| 212 | + |
| 213 | +if __name__ == "__main__": |
| 214 | + main() |
0 commit comments