GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — openshorts/llm_backend.py at main · VLab-Software/openshorts

Expand file tree

/

llm_backend.py

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
165 lines (133 loc) · 6.46 KB
/

llm_backend.py

Copy path

File metadata and controls

165 lines (133 loc) · 6.46 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
"""Text-only LLM backend for the moment picker: any OpenAI-compatible server.
Ollama, LM Studio, vLLM, llama.cpp's server, LocalAI and OpenRouter all speak
``POST {base}/chat/completions``. When ``LLM_BASE_URL`` is set (or
``LLM_PROVIDER=openai``), the transcript scoring and detail passes in
``main.get_viral_clips`` go here instead of Gemini, so a self-hosted install
can run the whole pipeline without a Google key.
What stays on Gemini, because it needs a model that can look at frames or a
video file: the layout picker (``layout_picker.py``), the on-screen content
detector (``screencast_layout.py``) and the silent-video path
(``main.get_visual_clips``). Without a Gemini key those degrade the way they
already did: the first two return "none", the third fails the job with a clear
message. Nothing in this module is imported by them.
Structured output: the prompts already spell out the exact JSON shape, so a
plain ``json_object`` mode is enough for most models. The request first asks
for ``json_schema`` (Ollama, vLLM, llama.cpp and LM Studio enforce it); a
server that rejects that field gets the same request again with
``json_object``, then with no ``response_format`` at all. Whatever comes back
is validated with the same pydantic model Gemini's ``response_schema`` uses,
so ``main.py`` sees one shape regardless of provider.
"""
from __future__ import annotations
import json
import os
from typing import Optional, Tuple, Type
import httpx
from pydantic import BaseModel
DEFAULT_MODEL = "llama3.1:8b"
DEFAULT_TIMEOUT = 600.0 # local models on CPU are slow; a scoring batch can take minutes
def provider() -> str:
"""``"openai"`` when a compatible endpoint is configured, else ``"gemini"``."""
explicit = (os.environ.get("LLM_PROVIDER") or "").strip().lower()
if explicit in ("openai", "ollama", "local", "openai-compatible"):
return "openai"
if explicit == "gemini":
return "gemini"
return "openai" if base_url() else "gemini"
def base_url() -> str:
return (os.environ.get("LLM_BASE_URL") or "").strip().rstrip("/")
def model_name() -> str:
return (os.environ.get("LLM_MODEL") or "").strip() or DEFAULT_MODEL
def active() -> bool:
"""True when the moment picker should call the OpenAI-compatible server."""
return provider() == "openai" and bool(base_url())
def describe() -> Optional[dict]:
"""What ``/api/config`` tells the dashboard, or ``None`` when inactive."""
if not active():
return None
return {"provider": "openai", "model": model_name(), "baseUrl": base_url()}
def _timeout() -> float:
try:
return float(os.environ.get("LLM_TIMEOUT") or DEFAULT_TIMEOUT)
except ValueError:
return DEFAULT_TIMEOUT
def _headers() -> dict:
# Ollama ignores the key but the OpenAI client convention (and vLLM with
# --api-key) wants the header present; "ollama" is the documented placeholder.
key = (os.environ.get("LLM_API_KEY") or "ollama").strip()
return {"Authorization": f"Bearer {key}", "Content-Type": "application/json"}
def _client(**kwargs) -> httpx.Client:
"""Factory so tests can swap in ``httpx.MockTransport``."""
return httpx.Client(timeout=_timeout(), **kwargs)
def _response_formats(schema: Type[BaseModel]):
name = getattr(schema, "__name__", "response").lower()
yield {"type": "json_schema",
"json_schema": {"name": name, "schema": schema.model_json_schema()}}
yield {"type": "json_object"}
yield None
def _is_format_rejection(resp: httpx.Response) -> bool:
if resp.status_code not in (400, 422):
return False
body = resp.text.lower()
return "response_format" in body or "json_schema" in body or "json_object" in body \
or "format" in body
def generate_json(prompt: str, schema: Type[BaseModel], model: Optional[str] = None,
) -> Tuple[dict, Optional[dict]]:
"""One chat completion that must come back as JSON matching ``schema``.
Returns ``(parsed_dict, cost_analysis)`` in the exact shape
``main._run_gemini_stage`` returns, so the caller does not branch on the
provider. Raises on HTTP errors, empty bodies and schema violations; the
retry policy lives in the caller, same as for Gemini.
"""
import gemini_worker # local import: keeps this module free of the google SDK
url = f"{base_url()}/chat/completions"
model = model or model_name()
messages = [
{"role": "system", "content": "You answer with a single JSON object and nothing else."},
{"role": "user", "content": prompt},
]
last_rejection: Optional[str] = None
with _client() as client:
for fmt in _response_formats(schema):
body = {"model": model, "messages": messages, "temperature": 0.2, "stream": False}
if fmt is not None:
body["response_format"] = fmt
resp = client.post(url, json=body, headers=_headers())
if fmt is not None and _is_format_rejection(resp):
# The server does not know this response_format flavour; the
# next loop iteration asks for a looser one.
last_rejection = resp.text[:200]
continue
if resp.status_code >= 400:
raise RuntimeError(
f"LLM server {resp.status_code} from {url}: {resp.text[:300]}")
data = resp.json()
break
else:
raise RuntimeError(
f"LLM server rejected every response_format variant: {last_rejection}")
choices = data.get("choices") or []
text = ""
if choices:
msg = choices[0].get("message") or {}
text = msg.get("content") or ""
if isinstance(text, list): # some servers return content parts
text = "".join(p.get("text", "") for p in text if isinstance(p, dict))
parsed = gemini_worker._parse_json_response_text(text)
# Validate against the same schema Gemini enforces server-side, so a
# local model that drops a field fails here with a readable error
# (retried by the caller) instead of deep inside the clip pipeline.
validated = schema.model_validate(parsed).model_dump()
usage = data.get("usage") or {}
cost = {
"input_tokens": int(usage.get("prompt_tokens") or 0),
"output_tokens": int(usage.get("completion_tokens") or 0),
"thinking_tokens": 0,
"input_cost": 0.0,
"output_cost": 0.0,
"total_cost": 0.0,
"model": model,
"price_estimated": False,
"local": True,
}
return validated, cost
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.