Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,18 @@ with `policyengine bundle status`. When run from `uvx` or `pipx`, the installer
creates or reuses `./.venv`; inside an existing virtualenv or conda environment,
it installs into the active environment.

Install the optional derivation narration extra with
`uv pip install "policyengine[narration]"`. `narrate()` and `narrate_async()` default to
`claude-sonnet-5-5`, low effort, and a 4,096-token budget including thinking.
The default route requires Anthropic credentials. When you select another
model with `model=`, use that provider's credentials. The default route omits
temperature. For other models, narration passes `max_tokens=500` and
`temperature=0.0` to LiteLLM by default and passes explicit overrides when
supplied. LiteLLM and the selected model must support the supplied values.
Narration text can vary between calls.
Keep `LITELLM_DROP_PARAMS` unset or `false`. Narration rejects parameter dropping
for Sonnet 5.5 because it can discard the required low-effort setting.

### For development

```bash
Expand Down
1 change: 1 addition & 0 deletions changelog.d/580.changed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Update optional derivation narration to Claude Sonnet 5.5 with low effort, a larger token budget, compatible LiteLLM routing, and no temperature override. Narration rejects incompatible global LiteLLM AnthropicConfig sampling settings and LiteLLM parameter dropping, which can discard the required effort setting.
4 changes: 4 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ dependencies = [
policyengine = "policyengine.cli:main"

[project.optional-dependencies]
narration = [
"litellm==1.103.0",
]
plotting = [
"plotly>=5.0.0",
]
Expand All @@ -55,6 +58,7 @@ us = [
"spm-calculator==1.0.0",
]
dev = [
"litellm==1.103.0",
"pytest",
"furo",
"autodoc_pydantic",
Expand Down
92 changes: 77 additions & 15 deletions src/policyengine/derivations/narrate.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,59 @@

from .trace import Derivation

DEFAULT_MODEL = "claude-sonnet-4-6"
DEFAULT_MAX_TOKENS = 500
DEFAULT_TEMPERATURE = 0.0
DEFAULT_MODEL = "claude-sonnet-5-5"
# Low effort plus a short narrative still needs room for thinking tokens.
DEFAULT_MAX_TOKENS = 4096


def _model_options(
model: str, max_tokens: int | None, temperature: float | None, *, litellm: Any
) -> dict[str, Any]:
if model in (DEFAULT_MODEL, f"anthropic/{DEFAULT_MODEL}"):
if temperature is not None:
raise ValueError("Sonnet 5.5 narration does not support temperature.")
if getattr(litellm, "drop_params", False):
raise ValueError(
"LiteLLM can drop Sonnet 5.5's low-effort output_config. "
"Disable LITELLM_DROP_PARAMS and set litellm.drop_params=False "
"before requesting narration."
)
# LiteLLM merges global Anthropic defaults after request arguments.
config = litellm.AnthropicConfig.get_config()
sampling_parameters = [
name
for name in ("temperature", "top_p", "top_k")
if config.get(name) is not None
]
if sampling_parameters:
raise ValueError(
"Sonnet 5.5 narration does not support LiteLLM AnthropicConfig "
f"sampling settings: {', '.join(sampling_parameters)}. "
"Clear these settings before requesting narration."
)
return {
"max_tokens": DEFAULT_MAX_TOKENS if max_tokens is None else max_tokens,
"custom_llm_provider": "anthropic",
# Pass the native option: reasoning_effort can add legacy thinking
# parameters in LiteLLM's provider translation.
"output_config": {"effort": "low"},
}
return {
"max_tokens": 500 if max_tokens is None else max_tokens,
"temperature": 0.0 if temperature is None else temperature,
}


def _response_text(response: Any) -> str:
if response.choices:
choice = response.choices[0]
if choice.finish_reason in ("refusal", "content_filter"):
raise ValueError("The narration model refused the request.")
# LiteLLM combines Anthropic text blocks and keeps thinking separately.
content = choice.message.content
if isinstance(content, str) and (text := content.strip()):
return text
raise ValueError("The narration model returned no text.")


def _build_prompt(
Expand Down Expand Up @@ -67,14 +117,22 @@ def narrate(
household_summary: str | None = None,
extra_context: str | None = None,
model: str = DEFAULT_MODEL,
max_tokens: int = DEFAULT_MAX_TOKENS,
temperature: float = DEFAULT_TEMPERATURE,
max_tokens: int | None = None,
temperature: float | None = None,
trace_max_depth: int = 8,
) -> str:
"""Synchronously ask an LLM to narrate this derivation.

Imports LiteLLM lazily so that ``import policyengine.derivations`` has no
LLM dependency. Returns the model's response text.
LLM dependency. Install ``policyengine[narration]`` to enable this feature.
Sonnet 5.5 uses low effort and a 4,096-token total budget by default.
You can override that budget. Keep global LiteLLM AnthropicConfig sampling
settings unset and ``drop_params`` false for Sonnet 5.5.
For other models, narration passes ``max_tokens=500`` and ``temperature=0.0``
to LiteLLM by default and passes explicit overrides when supplied. LiteLLM
and the selected model must support the supplied values.
Returns the model's response text. Raises ``ValueError`` on refusal, an
empty response, or incompatible Sonnet options.
"""
import litellm # noqa: PLC0415 — lazy import keeps the base module light

Expand All @@ -88,10 +146,9 @@ def narrate(
response = litellm.completion(
model=model,
messages=[{"role": "user", "content": prompt}],
temperature=temperature,
max_tokens=max_tokens,
**_model_options(model, max_tokens, temperature, litellm=litellm),
)
return response.choices[0].message.content.strip()
return _response_text(response)


async def narrate_async(
Expand All @@ -101,11 +158,17 @@ async def narrate_async(
household_summary: str | None = None,
extra_context: str | None = None,
model: str = DEFAULT_MODEL,
max_tokens: int = DEFAULT_MAX_TOKENS,
temperature: float = DEFAULT_TEMPERATURE,
max_tokens: int | None = None,
temperature: float | None = None,
trace_max_depth: int = 8,
) -> str:
"""Async variant of :func:`narrate` — same interface, awaitable result."""
"""Asynchronously ask an LLM to narrate this derivation.

See :func:`narrate` for Sonnet 5.5 options and response handling.
For other models, narration passes ``max_tokens=500`` and ``temperature=0.0``
to LiteLLM by default and passes explicit overrides when supplied. LiteLLM
and the selected model must support the supplied values.
"""
import litellm # noqa: PLC0415 — lazy import keeps the base module light

prompt = _build_prompt(
Expand All @@ -118,7 +181,6 @@ async def narrate_async(
response: Any = await litellm.acompletion(
model=model,
messages=[{"role": "user", "content": prompt}],
temperature=temperature,
max_tokens=max_tokens,
**_model_options(model, max_tokens, temperature, litellm=litellm),
)
return response.choices[0].message.content.strip()
return _response_text(response)
Loading
Loading