Files
stack/src/prisma/llm.py
kert 9b2a13797b
Some checks failed
CI / lint (push) Successful in 34s
CI / notebooks-smoke (push) Successful in 1m28s
Deploy / notebooks (push) Has been skipped
Deploy / zotero (push) Has been skipped
Deploy / docs (push) Has been skipped
Deploy / api (push) Has been skipped
Deploy / llm (push) Has been skipped
Deploy / mc (push) Has been skipped
Infra CI / notebooks (push) Successful in 48s
Infra CI / zotero (push) Successful in 14s
Infra CI / docs (push) Successful in 24s
Infra CI / api (push) Successful in 59s
Infra CI / llm (push) Successful in 46s
Infra CI / mc (push) Successful in 21s
Deploy / report (push) Successful in 13s
CI / test (push) Failing after 11m33s
style(prisma): ruff-format llm.py — unblock CI lint (refs P43)
2026-08-26 15:59:09 -04:00

351 lines
12 KiB
Python

"""Provider-agnostic LLM call abstraction.
Today the only backend is Anthropic's Messages API (prompt caching on
stable prefixes, tool use for structured output). Tomorrow an
OpenAI-compatible server (vLLM / Ollama / llama.cpp server) plugs in
behind the same :class:`Provider` Protocol — criteria-document prompts
ride on the server's automatic KV-cache reuse, tool schemas translate
1:1 (both vendors speak JSON-schema tool calling).
Environment selection (all optional; defaults favor Anthropic + Opus):
PRISMA_LLM_PROVIDER = anthropic | openai-compat (default: anthropic)
PRISMA_LLM_MODEL = claude-opus-4-6
PRISMA_LLM_BASE_URL = http://vllm:8000/v1 (openai-compat only)
ANTHROPIC_API_KEY = sk-ant-… (anthropic only)
OPENAI_API_KEY = optional auth for the compat server
Rule: anything provider-specific (cache_control markers, role quirks,
parallel tool-use headers) lives inside the provider class. Callers
hand us ``LLMCall`` and get back ``LLMResult`` — nothing else.
"""
from __future__ import annotations
import os
from dataclasses import dataclass, field
from typing import Any, Literal, Protocol
# ── Transport-neutral value objects ─────────────────────────────
Role = Literal["system", "user", "assistant"]
@dataclass
class LLMMessage:
"""One turn in the conversation.
``cache=True`` is a hint: on Anthropic it sets a cache_control
breakpoint; on OpenAI-compat it is ignored (server reuses KV cache
for any stable prefix automatically).
"""
role: Role
content: str
cache: bool = False
@dataclass
class LLMTool:
"""A structured-output target. Both vendors take JSON Schema."""
name: str
description: str
schema: dict[str, Any] # JSON Schema for the tool's input
@dataclass
class LLMCall:
messages: list[LLMMessage]
tools: list[LLMTool] = field(default_factory=list)
max_tokens: int = 4096
temperature: float = 0.0
# When tools present and ``force_tool`` is set, provider will compel a
# tool call (Anthropic: tool_choice={"type": "tool", "name": …};
# OpenAI: tool_choice={"type": "function", "function": {"name": …}}).
force_tool: str | None = None
@dataclass
class LLMResult:
"""A single completion response, normalized across providers."""
text: str
tool_calls: list[dict[str, Any]] # [{name: …, input: {…}}, …]
usage: dict[str, int] # input_tokens / output_tokens / cache_*
# ── Provider protocol ───────────────────────────────────────────
class Provider(Protocol):
"""Minimal surface every LLM backend must expose."""
def complete(self, call: LLMCall) -> LLMResult: ...
# ── Anthropic backend ───────────────────────────────────────────
class AnthropicProvider:
"""Anthropic Messages API with prompt caching on cache-flagged turns."""
def __init__(
self,
*,
model: str | None = None,
api_key: str | None = None,
) -> None:
# Lazy import so the `stack` CLI stays importable without the
# anthropic SDK when the prisma extras aren't installed.
import anthropic
self._model = model or os.environ.get("PRISMA_LLM_MODEL", "claude-opus-4-6")
self._client = anthropic.Anthropic(
api_key=api_key or os.environ.get("ANTHROPIC_API_KEY"),
)
def complete(self, call: LLMCall) -> LLMResult:
# Split off the system prompt — Anthropic wants it on a dedicated
# field, not in `messages`. We still honor cache flags on it by
# sending it as a list of blocks with cache_control on the final
# element when requested.
system_blocks: list[dict[str, Any]] = []
msgs: list[dict[str, Any]] = []
for m in call.messages:
if m.role == "system":
block: dict[str, Any] = {"type": "text", "text": m.content}
if m.cache:
block["cache_control"] = {"type": "ephemeral"}
system_blocks.append(block)
continue
content_blocks: list[dict[str, Any]] = [{"type": "text", "text": m.content}]
if m.cache:
content_blocks[-1]["cache_control"] = {"type": "ephemeral"}
msgs.append({"role": m.role, "content": content_blocks})
kwargs: dict[str, Any] = {
"model": self._model,
"max_tokens": call.max_tokens,
"temperature": call.temperature,
"messages": msgs,
}
if system_blocks:
kwargs["system"] = system_blocks
if call.tools:
kwargs["tools"] = [
{
"name": t.name,
"description": t.description,
"input_schema": t.schema,
}
for t in call.tools
]
if call.force_tool:
kwargs["tool_choice"] = {"type": "tool", "name": call.force_tool}
resp = self._client.messages.create(**kwargs)
text_parts: list[str] = []
tool_calls: list[dict[str, Any]] = []
for block in resp.content:
if block.type == "text":
text_parts.append(block.text)
elif block.type == "tool_use":
tool_calls.append({"name": block.name, "input": block.input})
usage = {
"input_tokens": getattr(resp.usage, "input_tokens", 0),
"output_tokens": getattr(resp.usage, "output_tokens", 0),
"cache_creation_input_tokens": getattr(
resp.usage,
"cache_creation_input_tokens",
0,
),
"cache_read_input_tokens": getattr(
resp.usage,
"cache_read_input_tokens",
0,
),
}
return LLMResult(text="".join(text_parts), tool_calls=tool_calls, usage=usage)
# ── OpenAI-compatible backend (vLLM / Ollama / llama.cpp-server) ─
class OpenAICompatProvider:
"""OpenAI-compatible chat-completions with tool calls.
Covers self-hosted inference servers that speak the OpenAI API
(vLLM, Ollama, llama.cpp's ``llama-server``, text-generation-webui,
LMStudio, …). Prompt caching is the server's problem — keep the
stable prefix first in the message list and the KV cache will reuse.
"""
def __init__(
self,
*,
model: str | None = None,
base_url: str | None = None,
api_key: str | None = None,
) -> None:
import openai # lazy — keeps dep optional
self._model = model or os.environ.get("PRISMA_LLM_MODEL", "llama-3.1-70b")
self._client = openai.OpenAI(
base_url=base_url or os.environ.get("PRISMA_LLM_BASE_URL"),
api_key=api_key or os.environ.get("OPENAI_API_KEY", "not-required"),
)
def complete(self, call: LLMCall) -> LLMResult:
# OpenAI-compat puts system messages in the same `messages` list.
# Cache flags are advisory (server decides KV reuse); we pass
# through unchanged.
msgs = [{"role": m.role, "content": m.content} for m in call.messages]
kwargs: dict[str, Any] = {
"model": self._model,
"max_tokens": call.max_tokens,
"temperature": call.temperature,
"messages": msgs,
}
if call.tools:
kwargs["tools"] = [
{
"type": "function",
"function": {
"name": t.name,
"description": t.description,
"parameters": t.schema,
},
}
for t in call.tools
]
if call.force_tool:
kwargs["tool_choice"] = {
"type": "function",
"function": {"name": call.force_tool},
}
resp = self._client.chat.completions.create(**kwargs)
msg = resp.choices[0].message
text = msg.content or ""
tool_calls: list[dict[str, Any]] = []
for tc in msg.tool_calls or []:
# OpenAI returns arguments as a JSON string — parse so
# downstream code sees the same dict shape as Anthropic.
import json as _json
try:
args = _json.loads(tc.function.arguments)
except (_json.JSONDecodeError, TypeError):
args = {}
tool_calls.append({"name": tc.function.name, "input": args})
usage = {
"input_tokens": resp.usage.prompt_tokens if resp.usage else 0,
"output_tokens": resp.usage.completion_tokens if resp.usage else 0,
"cache_creation_input_tokens": 0,
"cache_read_input_tokens": 0,
}
return LLMResult(text=text, tool_calls=tool_calls, usage=usage)
# ── Ollama native backend (fleet) ───────────────────────────────
class OllamaNativeProvider:
"""Native Ollama ``/api/chat`` — one instance per fleet host.
Speaks the native API rather than the OpenAI-compat ``/v1`` shim so
per-request ``options`` travel with the call (``num_ctx`` above the
4096 default, ``num_predict``, ``temperature``) — remote hosts then
need only a vanilla ``ollama pull`` of the model, no per-host
Modelfile variants (#654). ``force_tool`` has no native equivalent;
the screening prompt already elicits the tool call reliably.
"""
def __init__(self, *, host: str, model: str, num_ctx: int = 8192) -> None:
self._host = host.rstrip("/")
self._model = model
self._num_ctx = num_ctx
@property
def host(self) -> str:
return self._host
def complete(self, call: LLMCall) -> LLMResult:
import httpx # lazy — keeps module import light
payload: dict[str, Any] = {
"model": self._model,
"stream": False,
"messages": [{"role": m.role, "content": m.content} for m in call.messages],
"options": {
"temperature": call.temperature,
"num_ctx": self._num_ctx,
"num_predict": call.max_tokens,
},
}
if call.tools:
payload["tools"] = [
{
"type": "function",
"function": {
"name": t.name,
"description": t.description,
"parameters": t.schema,
},
}
for t in call.tools
]
resp = httpx.post(
f"{self._host}/api/chat",
json=payload,
timeout=httpx.Timeout(300.0, connect=5.0),
)
resp.raise_for_status()
data = resp.json()
msg = data.get("message") or {}
tool_calls: list[dict[str, Any]] = []
for tc in msg.get("tool_calls") or []:
fn = tc.get("function") or {}
args = fn.get("arguments")
if isinstance(args, str): # some builds stringify; normalize
import json as _json
try:
args = _json.loads(args)
except (ValueError, TypeError):
args = {}
tool_calls.append({"name": fn.get("name", ""), "input": args or {}})
return LLMResult(
text=msg.get("content") or "",
tool_calls=tool_calls,
usage={
"input_tokens": data.get("prompt_eval_count", 0),
"output_tokens": data.get("eval_count", 0),
"cache_creation_input_tokens": 0,
"cache_read_input_tokens": 0,
},
)
# ── Factory ─────────────────────────────────────────────────────
def make_provider() -> Provider:
"""Build the configured provider from environment.
The single entry point callers should use. Swap providers by
flipping ``PRISMA_LLM_PROVIDER`` in ``.env``; no code changes.
"""
kind = os.environ.get("PRISMA_LLM_PROVIDER", "anthropic").lower()
if kind == "anthropic":
return AnthropicProvider()
if kind in ("openai-compat", "openai", "vllm", "ollama"):
return OpenAICompatProvider()
raise ValueError(f"unknown PRISMA_LLM_PROVIDER: {kind!r}")