feat(llm): talk to OpenAI-compatible servers such as Strata

A base URL that ends in /v1 now selects the OpenAI-compatible API: chat goes
to /chat/completions and embeddings to /embeddings. The conversion lives in
src/jarvis/llm.py only, so the reply engine and every other caller keep their
Ollama-shaped messages and responses.

- Requests drop private engine keys, send tool-call arguments as JSON strings,
  map num_predict to max_tokens and the thinking switch to
  chat_template_kwargs.enable_thinking, and leave out num_ctx and keep_alive.
- Responses come back with message.content, tool calls with dict arguments and
  an id, and message.thinking from reasoning_content.
- Streaming, the warm-up (one-token chat completion), the intent judge and the
  dictation clean-up use the same path. A server without an embedding model
  fails open to the text paths.
- Specs and docs/llm_contexts.md describe the transport; roadmap records M3
  step 1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
javis-bot
2026-11-11 12:32:48 +09:00
parent beaacb39cd
commit 6b23a8adc7
11 changed files with 558 additions and 31 deletions

View File

@@ -6,6 +6,8 @@ import os
import sys
import requests
import json
import time
import uuid
def _caller_name() -> str:
@@ -35,6 +37,152 @@ class ToolsNotSupportedError(Exception):
pass
# ---------------------------------------------------------------------------
# OpenAI-compatible servers (Strata, llama.cpp, Ollama's own /v1)
# ---------------------------------------------------------------------------
#
# A base URL that ends in ``/v1`` selects the OpenAI chat-completions API.
# Callers keep building Ollama-shaped messages and reading Ollama-shaped
# responses (``message.content``, ``message.tool_calls`` with dict arguments,
# ``message.thinking``); the conversion lives here only. The server owns the
# context size, so ``num_ctx`` and ``keep_alive`` are not sent.
_OPENAI_MESSAGE_KEYS = ("role", "content", "tool_calls", "tool_call_id", "name")
def is_openai_compatible(base_url: str) -> bool:
"""True when ``base_url`` points at an OpenAI-compatible API (ends in ``/v1``)."""
return bool(base_url) and base_url.rstrip("/").endswith("/v1")
def _openai_messages(messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""Copy Ollama-shaped messages into OpenAI ones without changing the originals.
Private engine keys (``_is_tool_guidance``), ``thinking``, ``tool_name`` and
``tool_failed`` are dropped, and tool-call arguments become JSON strings.
"""
out: List[Dict[str, Any]] = []
for m in messages:
msg = {k: m[k] for k in _OPENAI_MESSAGE_KEYS if k in m}
if msg.get("content") is None:
msg["content"] = ""
calls = m.get("tool_calls")
if calls:
converted = []
for i, tc in enumerate(calls):
fn = tc.get("function") or {}
args = fn.get("arguments")
if not isinstance(args, str):
args = json.dumps(args or {}, ensure_ascii=False)
converted.append({
"id": tc.get("id") or f"call_{i}",
"type": "function",
"function": {"name": fn.get("name", ""), "arguments": args},
})
msg["tool_calls"] = converted
else:
msg.pop("tool_calls", None)
out.append(msg)
return out
def openai_chat_body(
chat_model: str,
messages: List[Dict[str, Any]],
*,
stream: bool,
thinking: bool,
max_tokens: Optional[int] = None,
temperature: Optional[float] = None,
tools: Optional[List[Dict[str, Any]]] = None,
) -> Dict[str, Any]:
body: Dict[str, Any] = {
"model": chat_model,
"messages": _openai_messages(messages),
"stream": stream,
# Qwen-family templates think unless told not to; spoken answers must not.
"chat_template_kwargs": {"enable_thinking": bool(thinking)},
}
if max_tokens is not None and max_tokens > 0:
body["max_tokens"] = int(max_tokens)
if temperature is not None:
body["temperature"] = temperature
if tools:
body["tools"] = tools
return body
def post_chat_completion(base_url: str, body: Dict[str, Any], timeout_sec: float, stream: bool = False):
"""POST ``body`` to ``<base_url>/chat/completions`` and return the response."""
return requests.post(
f"{base_url.rstrip('/')}/chat/completions", json=body, timeout=timeout_sec, stream=stream
)
def _parse_tool_arguments(raw: Any) -> Dict[str, Any]:
if isinstance(raw, dict):
return raw
if isinstance(raw, str) and raw.strip():
try:
parsed = json.loads(raw)
if isinstance(parsed, dict):
return parsed
except json.JSONDecodeError:
pass
debug_log(f"tool-call arguments are not a JSON object (len={len(raw)})", "llm")
return {}
def _ollama_shaped(data: Dict[str, Any]) -> Optional[Dict[str, Any]]:
"""Turn an OpenAI chat completion into the Ollama response shape callers read."""
choices = data.get("choices") if isinstance(data, dict) else None
if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict):
return None
choice = choices[0]
src = choice.get("message") or {}
msg: Dict[str, Any] = {"role": "assistant", "content": src.get("content") or ""}
reasoning = src.get("reasoning_content") or src.get("reasoning")
if reasoning:
msg["thinking"] = reasoning
calls = []
for tc in src.get("tool_calls") or []:
fn = tc.get("function") or {}
calls.append({
"id": tc.get("id") or f"call_{uuid.uuid4().hex[:8]}",
"type": "function",
"function": {"name": fn.get("name", ""), "arguments": _parse_tool_arguments(fn.get("arguments"))},
})
if calls:
msg["tool_calls"] = calls
return {"message": msg, "done": True, "done_reason": choice.get("finish_reason"), "usage": data.get("usage")}
def _log_openai_timing(data: Dict[str, Any], elapsed: float, caller: str) -> None:
"""Per-call latency line for OpenAI-compatible servers (no server-side phase split)."""
try:
usage = data.get("usage") or {}
print(
f" ⏱️ llm[{caller}] total={elapsed:.2f}s "
f"prompt={usage.get('prompt_tokens')}t gen={usage.get('completion_tokens')}t",
flush=True,
)
except Exception: # pragma: no cover - logging must never break a reply
pass
def _openai_chat(base_url: str, body: Dict[str, Any], timeout_sec: float, caller: str) -> Dict[str, Any]:
"""Non-streaming chat completion, returned in the Ollama shape. Raises requests errors."""
t0 = time.perf_counter()
with post_chat_completion(base_url, body, timeout_sec) as resp:
resp.raise_for_status()
data = resp.json()
_log_openai_timing(data, time.perf_counter() - t0, caller)
shaped = _ollama_shaped(data)
if shaped is None:
raise ValueError(f"no choices in response keys={list(data.keys()) if isinstance(data, dict) else type(data)}")
return shaped
def _log_ollama_timing(data: Dict[str, Any], num_ctx: int, caller: str) -> None:
"""Emit a one-line per-call latency breakdown so a slow voice turn can be
attributed to a specific internal LLM call (router / enrichment / digest /
@@ -81,6 +229,20 @@ def call_llm_direct(base_url: str, chat_model: str, system_prompt: str, user_con
{"role": "user", "content": user_content}
]
if is_openai_compatible(base_url):
caller = _caller_name()
body = openai_chat_body(chat_model, messages, stream=False, thinking=thinking, temperature=temperature)
try:
content = _openai_chat(base_url, body, timeout_sec, caller)["message"]["content"]
if content.strip():
return content
debug_log("call_llm_direct: empty content from OpenAI-compatible server", "llm")
except requests.exceptions.Timeout:
debug_log(f"call_llm_direct: timeout after {timeout_sec}s", "llm")
except Exception as e:
debug_log(f"call_llm_direct: request failed — {e}", "llm")
return None
options: Dict[str, Any] = {"num_ctx": num_ctx}
if temperature is not None:
options["temperature"] = temperature
@@ -150,6 +312,9 @@ def call_llm_streaming(
{"role": "user", "content": user_content}
]
if is_openai_compatible(base_url):
return _openai_stream(base_url, chat_model, messages, on_token, timeout_sec, thinking)
payload: Dict[str, Any] = {
"model": chat_model,
"messages": messages,
@@ -197,6 +362,49 @@ def call_llm_streaming(
return None
def _openai_stream(
base_url: str,
chat_model: str,
messages: List[Dict[str, Any]],
on_token: Optional[Callable[[str], None]],
timeout_sec: float,
thinking: bool,
) -> Optional[str]:
"""Server-sent-events stream from ``/chat/completions``; answer text only (no reasoning)."""
body = openai_chat_body(chat_model, messages, stream=True, thinking=thinking)
try:
with post_chat_completion(base_url, body, timeout_sec, stream=True) as resp:
resp.raise_for_status()
full_response = []
for line in resp.iter_lines():
if not line:
continue
text = line.decode("utf-8", "replace") if isinstance(line, bytes) else line
if not text.startswith("data:"):
continue
payload = text[5:].strip()
if payload == "[DONE]":
break
try:
chunk = json.loads(payload)
except json.JSONDecodeError:
continue
for choice in chunk.get("choices") or []:
content = (choice.get("delta") or {}).get("content")
if content:
full_response.append(content)
if on_token:
on_token(content)
result = "".join(full_response)
return result if result.strip() else None
except requests.exceptions.Timeout:
debug_log(f"call_llm_streaming: timeout after {timeout_sec}s", "llm")
return None
except Exception as e:
debug_log(f"call_llm_streaming: request failed — {e}", "llm")
return None
def extract_text_from_response(data: Dict[str, Any]) -> Optional[str]:
"""Extract text from LLM response - supports multiple response formats."""
# Preferred: Ollama chat non-stream format
@@ -251,6 +459,29 @@ def chat_with_messages(
Returns the parsed JSON response dict on success, or None on error/timeout.
"""
if is_openai_compatible(base_url):
opts = extra_options if isinstance(extra_options, dict) else {}
body = openai_chat_body(
chat_model, messages, stream=False, thinking=thinking,
max_tokens=opts.get("num_predict"), temperature=opts.get("temperature"), tools=tools,
)
caller = _caller_name()
try:
return _openai_chat(base_url, body, timeout_sec, caller)
except requests.exceptions.Timeout:
print(" ⏱️ LLM request timed out", flush=True)
except requests.exceptions.ConnectionError as e:
print(f" ❌ LLM connection error: {e}", flush=True)
except requests.exceptions.HTTPError as e:
if e.response is not None and e.response.status_code == 400 and tools:
raise ToolsNotSupportedError(
f"Model {chat_model!r} returned HTTP 400 — native tools API not supported"
)
print(f" ❌ LLM HTTP error: {e}", flush=True)
except Exception as e:
print(f" ❌ LLM error: {e}", flush=True)
return None
# Main agentic chat uses 8192 so the system prompt (tool list + protocol
# guidance + memory context) doesn't overflow and force ollama to truncate
# — which previously dropped the tool schema on smaller models like